【发布时间】:2019-07-16 16:21:41
【问题描述】:
这是在React:中调用setState的推荐方式
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
但是,这种格式仍然没有等待 setState 完成,然后才转到这段代码的下一行:
pressed = () => {
this.setState((prevState, props) => ({
token: 1
}), () => console.warn("TOKEN setState Callback: " + this.state.token));
console.warn("TOKEN before timeout: " + this.state.token);
setTimeout(function() {console.warn("TOKEN after timeout: " + this.state.token)}.bind(this), 500);
...
//rest of function
}
在这种情况下,这是输出的顺序
1. TOKEN setState 回调:1
2. 超时前TOKEN:0
3. 超时后TOKEN:0。
我不想将//rest of my function 放在回调中,因为它是一个相当长的函数。使函数“异步”并在 this.setState 前面加上 await 可以工作,但不建议在各种来源上使用。
为什么我的代码不起作用?如何在超时之前调用 TOKEN 之前完成 setState 调用,而无需大幅更改我的代码?
谢谢。
【问题讨论】:
-
创建一个函数并在设置状态回调中调用它
-
或者使用componentDidUpdate至于
Why doesn't my code work?,因为setState()是异步的。另外,为什么不想将函数的其余部分移到回调中呢?如果您的函数往往很长,您可能希望以不同的方式组织代码。
标签: javascript reactjs react-native asynchronous setstate