鍍金池/ 問答/HTML5  HTML/ react的setState放在定時器里面的問題?

react的setState放在定時器里面的問題?

state={

val:0

}
放在定時器了連續(xù)執(zhí)行兩次setState
clipboard.png

clipboard.png
去掉定時器連續(xù)執(zhí)行兩次setState
clipboard.png

clipboard.png

我看到的效果是 放在定時器里的兩次setState是同步的 而沒有定時器的話 兩次setState是異步的。這個有大神幫忙解釋一下嗎?

回答
編輯回答
夕顏

https://reactjs.org/docs/reac...
setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
以上是官方文檔對批量setState的解釋,只說了說setState會排隊(duì),但實(shí)際上,在當(dāng)前版本中,在不同的地方批量執(zhí)行setState會有不同的表現(xiàn)。

以下是官方文檔中給的一個鏈接,說明在什么時候setState會被批量處理
In depth: When and why are setState() calls batched?(深入了解:什么時候并且為什么setState()調(diào)用會被合并)

Currently (React 16 and earlier), only updates inside React event handlers are batched by default. There is an unstable API to force batching outside of event handlers for rare cases when you need it.

In future versions (probably React 17 and later), React will batch all updates by default so you won't have to think about this. As always, we will announce any changes about this on the React blog and in the release notes.
現(xiàn)在(React 16 和之前),在默認(rèn)情況下,只有直接在react生命周期React event handlers里寫的setState會被合并處理
未來版本(大概從React 17 開始),React會默認(rèn)合并所有的setState

下面官方文檔中給的另一個鏈接
In depth: Why isn’t this.state updated immediately?(深入了解:為什么this.state沒有被立刻更新?)

2018年7月30日 13:50
編輯回答
晚風(fēng)眠
2017年8月16日 12:15