简体   繁体   English

是否会立即反应setState设置状态?

[英]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. 我正在尝试使用setState存储值,但是我正在设置状态,并且在下一行中尝试console.log它,我无法在控制台中看到该值。

 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. 当我为此冲浪时,我看到setState是异步的,但是我无法理解。

You will not get the updated value of state just after calling setState(). 仅在调用setState()之后,您将不会获得状态的更新值。 This is because as soon as setState() is called view is re-rendered. 这是因为一旦调用setState(),就会重新渲染视图。 So it is better to check the updated value inside render or add callback function to setState. 因此,最好检查render中的更新值或将回调函数添加到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. setState()不会立即使this.state发生突变,但会创建一个挂起的状态转换。 Accessing this.state after calling this method can potentially return the existing value. 调用此方法后访问this.state可能会返回现有值。

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. 如果您要检查更新的状态,可以尝试将其记录在render方法中,因为一旦状态改变,react就会重新渲染。

The answer is it depends on when it is called. 答案是取决于何时调用。 setState() is executed immediately when called inside an event handler. 在事件处理程序内部调用setState()时将立即执行。 I believe it might also be synchronous before the component has mounted. 我相信组件安装之前也可能是同步的。

Basically every other time it will be called asynchronously. 基本上每隔一次它将被异步调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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