[英]Confusion with how setState works
I am confused with how setState works.我对 setState 的工作方式感到困惑。
Here is a portion of my code:这是我的代码的一部分:
handleBarsChange(value) {
this.setState({numberOfbars: value});
this.resetArray();
}
apparently, when the resetArray()
function executes and tries to access the this.state.numberOfbars
state variable, setState
hasn't updated the value yet.显然,当resetArray()
函数执行并尝试访问this.state.numberOfbars
状态变量时, setState
尚未更新该值。
I want some explanation on how and where should the setState be executed and when can i expect to see the change.我想要一些关于如何以及在何处执行 setState 以及何时可以看到更改的解释。
Thank you!谢谢!
setState
is asynchronous. setState
是异步的。 It has a second callback argument that can be used to run code after a state transition.它有第二个回调参数,可用于在状态转换后运行代码。 This isn't always the best approach, but with the very narrow example provided, it's hard to say.这并不总是最好的方法,但由于提供了非常狭窄的示例,这很难说。
this.setState({numberOfBars: value}, () => { this.resetArray() })
From the react docs:从反应文档:
The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. setState() 的第二个参数是一个可选的回调函数,一旦 setState 完成并重新渲染组件,就会执行该回调函数。 Generally we recommend using componentDidUpdate() for such logic instead.通常我们建议使用 componentDidUpdate() 来代替这种逻辑。
https://reactjs.org/docs/react-component.html#setstate https://reactjs.org/docs/react-component.html#setstate
The fact is that setState()
function is async so even if you run code after you call it, some state may not be updated yet.事实是setState()
函数是异步的,因此即使您在调用它之后运行代码,某些状态可能还没有更新。
The solution is implement a callback when the state was updated succesfully ( setState(<state>, <callback>)
), for example:解决方案是在状态更新成功时实现回调( setState(<state>, <callback>)
),例如:
handleBarsChange(value){
this.setState({numberOfbars: value}, () => {
this.resetArray();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.