Is setstate asynchronous or synchronous in react?

Nickyang 2021-09-15 10:51:24

setState() Attention to the use of :

1. Don't modify state

 example :this.state.count = 2;
This is a wrong way of writing ,react Components do not render updates
Proper use :
this.setState({count:2})
 Copy code 

2.state stay React Updates are asynchronous in composite events

 For performance reasons ,react Will be more than one setState() Merge into one call , Batch updates are done asynchronously
, Here's the code for the test , We can look at the output
 Copy code 

image.png When I first clicked , Called handleChangeCount Methods , And then call this.setState updated , And this count The value will not be updated inside , So the first time console.log The output value is 0 instead of 1, So we can conclude that at this time state An update of is an asynchronous image.png

If we want to get the latest count value , We can get the latest through callback count value

image.png The output results are shown in the figure below image.png

3.state stay setTimeOut Synchronized with native Events

(1)setTimeout test : image.png Use setTimeout The output is as follows image.png (2) Native event testing : image.png Using native events, the output results are as follows image.png

Conclusion :setState Only in react Composite events and lifecycle functions are asynchronous , stay setTimeout Synchronized with native Events

Please bring the original link to reprint ,thank
Similar articles

2021-09-15

2021-09-15