为什么 reactjs Async 中的 setState 而不是 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.

现在我搜索并找到了这个博客(setState() 状态突变操作在 ReactJS 中可能是同步的)

Now I searched and found this blog (setState() State Mutation Operation May Be Synchronous In ReactJS)

这里他发现setState是async(栈空时调用)还是sync(一调用就调用)取决于状态变化是如何触发的.

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.

现在这两件事很难消化

  1. 在博客中 setState 函数是在函数 updateState 内部调用的,但触发 updateState 函数的不是被调用函数会知道的.
  2. 他们为什么要让 setState 异步,因为 JS 是单线程语言,而且这个 setState 不是 WebAPI 或服务器调用,所以只能在 JS 的线程上完成.他们这样做是为了让重新渲染不会停止所有事件侦听器和东西,还是存在其他一些设计问题.
  1. In the blog the setState function is called inside a function updateState, but what triggered the updateState function is not something that a called function would know about.
  2. 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:

代替:

this.setState({foo: "one"}, () => {
    this.setState({bar: "two"});
});

这样做:

this.setState({
    foo: "one",
    bar: "two"
});

相关文章