Reactjs-setState的先前状态是第一个参数,props是第二个参数 [英] Reactjs-setState previous state is the first argument, props as the second argument
问题描述
我已经在这篇官方文章中阅读了以下内容:
I have read in this official article these lines:
this.props
和this.state
可以异步更新,您不应依赖于它们的值来计算下一个状态.
this.props
andthis.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
任何人都可以通过举例说明以下代码试图达到的目的.
Can anyone please explain to me what the following code is trying to achieve by giving an example.
this.setState((prevState, props) => ({
couter: prevState.counter + props.increment
}));
推荐答案
他们说您应该这样做,而不是下面的示例.
They say you should do like that instead of the below example.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
如果您这样访问,他们将无法确保状态将具有正确的值,因为 setState()将异步发生,可能会发生其他更新并更改该值.如果要基于先前的状态来计算状态,则必须确保具有最新的值,因此它们使 setState()接受一个函数,该函数使用 prevState 和 props ,因此您可以使用正确的值来更新状态,如下面的示例.
They can't assure the state will have the correct value if you access like this because setState() will happen asynchronously, other updates could occur and change the value. If you are going to calculate the state based on the previous state, you have to make sure you have the last and most up to date value, so they made setState() accept a function that is called with prevState and props, so you can have the correct value to update your state, like the example below.
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
这篇关于Reactjs-setState的先前状态是第一个参数,props是第二个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!