React 中 setState() 之后的代码会是 运行 吗?
Will code after setState() in React be run?
试图了解 React 中 setState() 的工作原理。我的问题是这样的。
如果我有一个函数,其中一行是 setState(),那么在重新渲染之前,此行之后的代码行是否仍然是 运行?例如,在下面的代码中,
foo(value) {
this.setState({stateValue: value});
console.log("Stuff after setState");
}
在该代码中,console.log 是否保证为 运行?它 运行s 当我测试它时,但我不确定这是否只是因为 React 还没有时间重新渲染。我可以期待 this.setState() 到 运行 之后的代码吗?
setState
是 asynchronous
函数,就像任何异步函数被传递到事件循环一样,setState
也被传递到事件循环及其后的任何代码将无缝执行。
一旦 setState 方法执行完成,它会触发 render 方法,此时 React 将处理文档渲染。
让我们看看 setState documentation
Think of setState() as a request rather than an immediate command to update the component
React does not guarantee that the state changes are applied immediately
将其视为 setTimeout(function test() {...}, 0);
一条消息将被添加到队列中,test
函数将在所有堆栈为空之前不会被触发。您可以在 EventLoop documentation
上找到更多信息
试图了解 React 中 setState() 的工作原理。我的问题是这样的。
如果我有一个函数,其中一行是 setState(),那么在重新渲染之前,此行之后的代码行是否仍然是 运行?例如,在下面的代码中,
foo(value) {
this.setState({stateValue: value});
console.log("Stuff after setState");
}
在该代码中,console.log 是否保证为 运行?它 运行s 当我测试它时,但我不确定这是否只是因为 React 还没有时间重新渲染。我可以期待 this.setState() 到 运行 之后的代码吗?
setState
是 asynchronous
函数,就像任何异步函数被传递到事件循环一样,setState
也被传递到事件循环及其后的任何代码将无缝执行。
一旦 setState 方法执行完成,它会触发 render 方法,此时 React 将处理文档渲染。
让我们看看 setState documentation
Think of setState() as a request rather than an immediate command to update the component
React does not guarantee that the state changes are applied immediately
将其视为 setTimeout(function test() {...}, 0);
一条消息将被添加到队列中,test
函数将在所有堆栈为空之前不会被触发。您可以在 EventLoop documentation