Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【2021-07-21】React 中 setState 什么时候是同步的,什么时候是异步的? #12

Open
superDCH opened this issue Jul 21, 2021 · 1 comment
Labels

Comments

@superDCH
Copy link
Owner

No description provided.

@superDCH superDCH added the react label Jul 21, 2021
@superDCH
Copy link
Owner Author

由React控制的事件处理程序,以及生命周期函数调用setState不会同步更新state 。

同步更新:React控制之外的事件中调用setState,比如原生js绑定的事件,setTimeout/setInterval等。

异步更新:由React控制的事件处理程序,以及生命周期函数调用setState不会同步更新state 。大部分开发中用到的都是React封装的事件,比如onChange、onClick、onTouchMove等,这些事件处理程序中的setState都是异步处理的。

原因:在React的setState函数实现中,会根据一个变量isBatchingUpdates判断是直接更新this.state还是放到队列中回头再说,而isBatchingUpdates默认是false,也就表示setState会同步更新this.state,但是,有一个函数batchedUpdates,这个函数会把isBatchingUpdates修改为true,而当React在调用事件处理函数之前就会调用这个batchedUpdates,造成的后果,就是由React控制的事件处理过程setState不会同步更新this.state。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant