description
setStateupdatesstatethrough a queue mechanism. WhensetStateis executed, thestatethat needs to be updated will be merged and put into the status queue, instead of updatingthis.stateimmediately. The queue mechanism can updatestatein batches efficiently.
example:
constructor(){
this.state={
val:0,
}
}
componentDidMount(){
this.setState({val:this.state.val+1});
console.log(this.state.val);
this.setState({val:this.state.val+1});
console.log(this.state.val);
setTimeout(()=>{
this.setState({val:this.state.val+1});
console.log(this.state.val);
this.setState({val:this.state.val+1});
console.log(this.state.val);
},0);
}
result: 0re0pence2penny 3
problem description
Why not 0pl 0pl 2jol 2?
- 0re0jue 2 can understand that the first two updates are still in batch, so merge setState, first and get the result only the next time render.
- when setTimeout is executed, the first setState is updated to false, in batches at this time, but why does this setState not change the component state to batch update status? This triggers the batch update transaction and causes the two setState in the timer to merge?
is very confusing, the feeling contradicts with the explained setState mechanism, but the result is executed separately.
