[英]Will react setState immedietly set the state?
我正在尝试使用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);
当我为此冲浪时,我看到setState是异步的,但是我无法理解。
仅在调用setState()之后,您将不会获得状态的更新值。 这是因为一旦调用setState(),就会重新渲染视图。 因此,最好检查render中的更新值或将回调函数添加到setState。
例:
this.setState({"myCountry": country},function(){console.log(this.state.myCountry)});
要么,
render: function() {
console.log(this.state.myCountry)
}
没有
setState()不会立即使this.state发生突变,但会创建一个挂起的状态转换。 调用此方法后访问this.state可能会返回现有值。
如果您要检查更新的状态,可以尝试将其记录在render方法中,因为一旦状态改变,react就会重新渲染。
答案是取决于何时调用。 在事件处理程序内部调用setState()时将立即执行。 我相信组件安装之前也可能是同步的。
基本上每隔一次它将被异步调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.