为什么setState in reactjs Async而不是Sync? [英] Why is setState in reactjs Async instead of Sync?
问题描述
我刚刚发现在react 中,任何组件中的this.setState()
函数都是异步的,或者在调用它的函数完成后调用。
I have just found that in react this.setState()
function in any component is asynchronous or is called after the completion of the function that it was called in.
现在我搜索并找到了这个博客( http://www.bennadel.com/blog/2893-setstate-state-mutation-operation-may-be-synchronous-in-reactjs.htm )
Now I searched and found this blog (http://www.bennadel.com/blog/2893-setstate-state-mutation-operation-may-be-synchronous-in-reactjs.htm)
在这里,他发现 setState
是异步(当堆栈为空时调用)或同步(根据被触发的状态变化的方式调用。)
Here he found that setState
is async(called when stack is empty) or sync(called as soon as called) depending on how the change of state was triggered.
现在这两件事很难消化
- 在博客中,在函数
updateState
中调用setState
函数,但是什么触发了updateState
函数并不是被调用函数会知道的。 - 为什么它们会产生
setSt ate
async,因为JS是单线程语言,这个setState不是WebAPI或服务器调用,所以必须只在JS的线程上完成。他们是这样做的,以便重新渲染不会停止所有事件监听器和东西,或者存在其他一些设计问题。
- In the blog the
setState
function is called inside a functionupdateState
, but what triggered theupdateState
function is not something that a called function would know about. - Why would they make
setState
async as JS is single threaded language and this setState is not a WebAPI or server call so has to be done on JS's thread only. Are they doing this so that Re-Rendering does not stop all the event listeners and stuff, or there is some other design issue.
推荐答案
您可以在状态值更新后调用函数:
You can call a function after the state value has updated:
this.setState({foo: 'bar'}, () => {
// Do something here.
});
此外,如果您有很多州要立即更新,请将它们全部归入同一 setState
:
Also, if you have lots of states to update at once, group them all within the same setState
:
Instead of:
this.setState({foo: "one"}, () => {
this.setState({bar: "two"});
});
just do this:
this.setState({
foo: "one",
bar: "two"
});
这篇关于为什么setState in reactjs Async而不是Sync?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!