gpt4 book ai didi

reactjs - React, 2 setstate 在同一个函数 : second one erase the first

转载 作者:行者123 更新时间:2023-12-01 06:15:37 26 4
gpt4 key购买 nike

我正在尝试运行上面的代码,但状态只会针对 idx 进行更新。据我了解,第二个函数的 setState 不会获得更新状态,这就是发生这种情况的原因。有没有办法让它正常工作(期待而不是将 2 个功能合并为一个)

doIt(idx,array) {
this.doFirst(array);
this.doSecond(idx);
}

doFirst(array){
//bla bla bla code
this.setState(test: {...this.state.test, array});
}

doSecond(idx) {
// bla bla bla code
this.setState(test: {...this.state.test, idx});
}

最佳答案

setState() 是异步的。

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

它需要一个可选的回调函数,一旦 setState 完成并且组件被重新渲染,该回调函数就会被执行。你可以使用那个回调。

如果下一个状态依赖于上一个状态,建议使用更新函数形式setState(updater[, callback])

doIt(idx,array) {
this.doFirst(array, () => this.doSecond(idx));
}

doFirst(array, callback){
//bla bla bla code
this.setState(firstUpdaterFunction, callback);
}

doSecond(idx) {
// bla bla bla code
this.setState(2ndUpdaterFunction);
}

引用资料:

https://reactjs.org/docs/react-component.html#setstate

https://stackoverflow.com/a/41446620/2073920

关于reactjs - React, 2 setstate 在同一个函数 : second one erase the first,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50648505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com