gpt4 book ai didi

javascript - react : potential race condition for Controlled Components

转载 作者:数据小太阳 更新时间:2023-10-29 05:14:03 26 4
gpt4 key购买 nike

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.

问:是否可能出现以下情况:

  1. handleChange 被触发;
  2. setState 在 React 中排队;
  3. handleSubmit 被触发,它读取 this.state.value 的过时值;
  4. 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.

让我们来看看发生了什么(要点):

  1. 进入handleChange react 事件处理器;
  2. 所有setState调用都在内部进行了批处理;
  3. 退出 handleChange
  4. 刷新 setState 更改
  5. render 被调用
  6. 进入handleSubmit
  7. this.state 访问正确提交的值
  8. 正在退出 handleSubmit

因此,如您所见,只要在 React 事件处理程序中安排更新,就不会发生竞争条件,因为 React 提交所有批处理的 state 在每个事件处理程序调用结束时更新。

关于javascript - react : potential race condition for Controlled Components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53316501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com