React in the SetState is synchronous or asynchronous troubled for a long time, today finally has the answer; it is both synchronous and asynchronous;
Batch update:
Join me on the page to write three setstate to go to the separate
Componentdidmount () {this.setstate ({ val: this.state.val + 1}) Console.log (1) this.setstate ({ val: this.state.val + 1}) console.log (2) this.setState ({ val: this.state.val + 1}) console.log (3) } /span> values printed in render is: 3; This means that setstate is synchronous; join I want to enter Val value in the execution of other +, can use settimeout or use the second parameter of SetState callback;In
setState
, react creates an internal
updateQueue
Pass
firstUpdate
、
lastUpdate
、
lastUpdate.next
To maintain an updated queue, in the final
performWork
, the same key will be overwritten
State = {val: 0} Componentdidmount () {SetTimeout (_ = = { This.setstate ({ val: this.state.val + 1}) Console.log (this.state.val) //Output updated value--1}, 0) }Componentdidmount () {this.setstate ({ val: this.state.val + 1}) Console.log (this.state.val) //Output or value before update- 0} In fact, as with synthetic events, when
componentDidmount
When executed, the react internal is not updated, the execution is finished
componentDidmount
Before you go
commitUpdateQueue
Update. This leads you to
componentDidmount
In
setState
The result of going to Console.log is still the value before the update. Therefore, the State should be updated in the Componentwillmount;
setState
Is "asynchronous" only in synthetic events and hooks, and is synchronous in both the native event and the hook function setTimeout
.
setState
"Async" does not mean that the internal asynchronous code implementation, in fact, the process and code are synchronous, but the synthesis event and hook function call order before the update, resulting in the synthesis event and hook function can not immediately get the updated value, form the so-called "asynchronous", of course, the second parameter The callback in SetState (Partialstate, callback) gets the updated results.
setState
Batch update optimization is also based on "asynchronous" (synthetic events, hook functions), in the native events and settimeout not bulk update, in "async" if the same value is repeated setState
, setState
the bulk update policy will overwrite it, take the last execution, If you have multiple different values at the same time, they are setState
combined for batch updates when they are updated.
Links: https://juejin.im/post/5b45c57c51882519790c7441
is setstate asynchronous or synchronous?