简体   繁体   中英

Will react setState immedietly set the state?

I am trying to store a value using setState, however I am setting the state and in next line I am trying to console.log it, I am not able to see the value in the console.

 getInitialState: function(){ return{ myCountry: "" } } var country = event.target.value; this.setState({"myCountry": country}); console.log(this.state.myCountry); //prints nothing console.log(event.target.value); 

When I surfed for this I saw that setState is asynchronous, but I am not able to understand.

You will not get the updated value of state just after calling setState(). This is because as soon as setState() is called view is re-rendered. So it is better to check the updated value inside render or add callback function to setState.
Example:

this.setState({"myCountry": country},function(){console.log(this.state.myCountry)});

Or,

render: function() {
    console.log(this.state.myCountry)
}

NO

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

IF you want to check the updated state you can try logging it in render method as react will anyhow re-render once the state is changed.

The answer is it depends on when it is called. setState() is executed immediately when called inside an event handler. I believe it might also be synchronous before the component has mounted.

Basically every other time it will be called asynchronously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM