为什么reactjs Async 中的setState 是Async 而不是Sync? [英] Why is setState in reactjs Async instead of Sync?

查看:25
本文介绍了为什么reactjs Async 中的setState 是Async 而不是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 是异步的(当堆栈为空时调用)还是同步的(一被调用就调用),这取决于状态变化是如何触发的.

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"
});

这篇关于为什么reactjs Async 中的setState 是Async 而不是Sync?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆