简体   繁体   English

导致setState(React)异步的代码在哪里?

[英]Where is the code that causes setState (React) to be asynchronous?

I recently read through a large portion of the React and ReactDOM codebase in order to get an understanding of what happens when a call to setState occurs. 我最近阅读了React和ReactDOM代码库的大部分内容,以了解调用setState时发生的情况。 At this point, I would say that I understand the sequence of events at a high level. 在这一点上,我想说的是我对事件的顺序有较高的了解。 A call to setState results in a message being added to a queue of updates that need to be processed. 对setState的调用导致将消息添加到需要处理的更新队列中。 The updates are processed and changes to the DOM are only made if necessary. 处理更新,仅在必要时对DOM进行更改。

Here's where I am lost. 这是我迷路的地方。 There are hundreds of blog posts discussing the asynchronous behavior of setState. 有数百篇博客文章讨论了setState的异步行为。 While I don't doubt that setState is asynchronous, I cannot find a line of code in the ReactDOM codebase that would introduce asynchronous behavior. 尽管我毫不怀疑setState是异步的,但我无法在ReactDOM代码库中找到会引入异步行为的代码行。 Does anyone know exactly where this happens? 有人知道这到底发生在哪里吗?

First of all setState may be execute in async way, but it is not allwys executed as such. 首先, setState可以异步方式执行,但并非如此。 Ben Nadel list some of his findings in setState() State Mutation Operation May Be Synchronous In ReactJS Ben Nadel列出了他在setState()中的一些发现: 状态变异操作在ReactJS中可能是同步的

To summarize setStates seems to gets batched in situations where react can intercept originating event, like onClick handlers. 总而言之, setStates似乎在react可以拦截原始事件(例如onClick处理程序)的情况下被批处理。 Since react creates actual DOM from virtual react DOM (and since it is aware of semantics of attributes) it can wrap any of onClick handlers that you provide into something like this 由于react通过虚拟的React DOM创建了实际的DOM(并且由于它知道属性的语义),因此可以将您提供的任何onClick处理程序包装成这样的内容

wrappedHandler = () => {
  turnBatchingOn()
  originalHanlder()
  executeBatched()
}

In this case you get async behavior, all setState calls get enqueued, and they get executed only after your original onClick handler has finished executing. 在这种情况下,您将获得异步行为,所有setState调用都将入队,并且只有在原始的onClick处理程序执行完之后,它们才被执行。

Note this is not actual react code it is just my speculation how it is async effect achieved. 注意这不是实际的反应代码,这只是我的猜测,它是如何实现异步效果的。 I understand it is not actual line of code that does it, but I think it could help you find it. 我了解并不是执行此操作的实际代码行,但我认为它可以帮助您找到它。

Best article explaining setState implementation that I found is on React Kung Fu 最佳的解释我发现的setState实现的文章在React Kung Fu上

我认为setState不是异步的,但是有多个setState调用的优化,在某些情况下可以保证同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM