When setState synchronous, asynchronous and when, and why?

When setState synchronous, asynchronous and when and why

Answer: When React library control, asynchronous; or synchronized.

Sample code is as follows:

constructor(props){
    super(porps);
    this.state = {
        name:"异步"
    }
}
test(){
    this.setState({
        name:"同步"
    })
    alert(this.state.name)
}
<TouchableOpacity onPress={()=>this.test()}>
    <Text>Button</Text>
</TouchableOpacity> 
TouchableOpacity above, control is React library, this time using setState was asynchronous, Alert is "asynchronous." 

How to trigger synchronization it? Look at the following code:

test(){
    this.setState({
        name:"同步"
    },function(){
        alert(this.state.name)
    })
}

  At this point the way to use the callback to trigger synchronization, the majority of events are React package used in the development, such as onChange, onClick, onTouchMove, etc. These event handlers in setState are asynchronous processing.

 

React is how to control both asynchronous and synchronous it?

React in setState function implementation, the determination based on a variable is updated directly this.state isBatchingUpdates into the queue delay or updated, and the default isBatchingUpdates is false, indicating that gets updated setState this.state; however, there is a function batchedUpdates the function will isBatchingUpdates amended as true, and when before React calling the event handler will first call will isBatchingUpdates modify this batchedUpdates true, so controlled by React event processing setState not synchronize updates this.state.


 




 

Guess you like

Origin www.cnblogs.com/gooldns/p/11907812.html