为什么调用 react setState 方法不会立即改变状态? [英] Why calling react setState method doesn't mutate the state immediately?
问题描述
我正在阅读表单部分class="post-tag" title="show questions tagged 'reactjs'" rel="tag">reactjs 文档并尝试使用此代码来演示 onChange
用法(JSBIN).
I'm reading Forms section of reactjs documentation and just tried this code to demonstrate onChange
usage (JSBIN).
var React= require('react');
var ControlledForm= React.createClass({
getInitialState: function() {
return {
value: "initial value"
};
},
handleChange: function(event) {
console.log(this.state.value);
this.setState({value: event.target.value});
console.log(this.state.value);
},
render: function() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange}/>
);
}
});
React.render(
<ControlledForm/>,
document.getElementById('mount')
);
当我在浏览器中更新 值时,
handleChange
回调中的第二个 console.log
会打印和第一个console.log
一样的value
,为什么我看不到this.setState({value: event.target.value})<的结果/code> 在
handleChange
回调范围内?
When I update the <input/>
value in the browser, the second console.log
inside the handleChange
callback prints the same value
as the first console.log
, Why I can't see the result of this.setState({value: event.target.value})
in the scope of handleChange
callback?
推荐答案
来自 React 的 文档:
From React's documentation:
setState()
不会立即改变 this.state
而是创建一个待处理的状态转换.调用 this 后访问 this.state
方法可能会返回现有值.没有保证对setState
的调用和调用的同步操作进行批处理以提高性能.
setState()
does not immediately mutatethis.state
but creates a pending state transition. Accessingthis.state
after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls tosetState
and calls may be batched for performance gains.
如果你想在状态改变发生后执行一个函数,把它作为回调传入.
If you want a function to be executed after the state change occurs, pass it in as a callback.
this.setState({value: event.target.value}, function () {
console.log(this.state.value);
});
这篇关于为什么调用 react setState 方法不会立即改变状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!