the React tutorial中有如下代码:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
还有a warning关于setState 方法:
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.
问:是否可能出现以下情况:
- handleChange 被触发;
- setState 在 React 中排队;
- handleSubmit 被触发,它读取 this.state.value 的过时值;
- setState 实际处理。
或者有某种保护措施可以防止这种情况发生?
最佳答案
希望this 回答你的问题:
In React 16, if you call setState inside a React event handler, it is flushed when React exits the browser event handler. So it's not synchronous but happens in the same top-level stack.
In React 16, if you call setState outside a React event handler, it is flushed immediately.
让我们来看看发生了什么(要点):
- 进入
handleChange
react 事件处理器; - 所有
setState
调用都在内部进行了批处理; - 退出
handleChange
- 刷新
setState
更改 render
被调用- 进入
handleSubmit
- 从
this.state
访问正确提交的值 - 正在退出
handleSubmit
因此,如您所见,只要在 React
事件处理程序中安排更新,就不会发生竞争条件,因为 React
提交所有批处理的 state
在每个事件处理程序调用结束时更新。
关于javascript - react : potential race condition for Controlled Components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53316501/