Use of setState() note:
1. Do not modify state directly
Example: this.state.count = 2; This.setstate ({count:2}) {this.setstate ({count:2});}Copy the code
2. State updates asynchronously in React composited events
React merges setState() into a single call for performance purposes, and updates it asynchronously in batches. Here is the code for the test, and we can see the outputCopy the code
When I first click, I call the handleChangeCount method, and then CALL this.setState to update it, and the count value is not updated inside, so the first console.log output is 0 instead of 1, So we can conclude that an update of state is asynchronous
If we want to get the latest count, we can call a callback to get the latest count
The output is shown below
3. State is synchronized in setTimeOut and native events
(1) the setTimeout test: Using setTimeout produces the following output (2) Native event test: Using native events, the output is as follows
Conclusion: setState is only asynchronous in React synthetic events and lifecycle functions, and synchronous in setTimeout and native events