【发布时间】:2020-01-04 21:44:00
【问题描述】:
我的 React 组件中有几个方法,所有这些方法都会修改状态:
class Abc extends React.Component {
state = {
f1 : 'f1',
f2 : 'f2',
f3 : 'f2',
dynamicValue : 'some initial value',
}
func1 = () => {
//..do some work
this.setState({ f1 : someValue1})
}
func2 = () => {
//..do some work
this.setState({ f2 : someValue2})
}
func3 = () => {
//..do some work
this.setState({ f3 : someValue3})
}
doWorkAfterAllSetStateIsComplete = () => {
const val = this.state.dynamicValue;
// I get stale state here
}
doWork = () => {
func1();
func2();
func3();
doWorkAfterAllSetStateIsComplete();
}
}
如果我像这样在setTimeout 中调用doWorkAfterAllSetStateIsComplete,我会得到更新的状态。
setTimeout(() => {
doWorkAfterAllSetStateIsComplete();
// this.state.dynamicValue is updated here.
}, 0)
我知道这是因为setState 是async 和setTimeout 在JavaScript 的下一个“滴答”中调用doWorkAfterAllSetStateIsComplete,所以我在doWorkAfterAllSetStateIsComplete 中获得了更新的状态值。但这对我来说似乎有点 hacky。还有其他方法可以实现吗?
【问题讨论】:
-
这是一个你可以玩的演示。codepen.io/oze4/pen/dybzLPK?editors=1011
标签: reactjs