jjzjj

javascript - Reactjs-setState previous state为第一个参数,props为第二个参数

coder 2024-05-17 原文

我在这篇官方文章中读到了以下几行:

this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

任何人都可以通过示例向我解释以下代码试图实现什么。

 this.setState((prevState, props) => ({
  couter: prevState.counter + props.increment
}));

I am referring to this official website of reactjs React.js

最佳答案

他们说你应该这样做而不是下面的例子。

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

如果您像这样访问,他们无法确保状态将具有正确的值,因为 setState() 将异步发生,其他更新可能发生并更改值。如果你要根据以前的状态计算状态,你必须确保你有最后的和最新的值,所以他们让 setState() 接受一个调用的函数prevStateprops,因此您可以使用正确的值来更新您的状态,如下例所示。

 // Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

关于javascript - Reactjs-setState previous state为第一个参数,props为第二个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50837670/

有关javascript - Reactjs-setState previous state为第一个参数,props为第二个参数的更多相关文章

随机推荐