gpt4 book ai didi

reactjs - 在setState中使用函数返回对象和直接使用对象有什么区别?

转载 作者:行者123 更新时间:2023-12-03 14:30:15 25 4
gpt4 key购买 nike

下面,当我在 setState 内部使用函数返回对象时,handleChange 方法会抛出错误,但当我直接将 inputvalue 作为对象更新时工作正常

   class App extends React.Component {
constructor (props) {
super(props);
this.state = {
inputvalue: ''
}
this.handleChange = this.handleChange.bind(this);
}

handleChange (event) {
event.preventDefault();
this.setState(() => {
return {inputvalue: event.target.elements.name.value}//throws an error but works fine if I use just use object with out using a functon to return
}
);
}

render() {
return (
<div>
<form onSubmit={this.handleChange}>
<label>Name </label>
<input type="text" name="option" />
<button>submit</button>
</form>
<p> {this.state.inputvalue}</p>
</div>
);
}
}

render(<App />, document.getElementById('app'));

发生的警告:

警告:出于性能原因,会重用此合成事件。如果您看到此内容,则说明您正在访问已发布/无效的合成事件的 stopPropagation 方法。这是一个无操作函数。如果必须保留原始合成事件,请使用 event.persist()。请参阅https://reactjs.org/docs/events.html了解更多信息。

最佳答案

基于此:

the SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

使用函数作为更新程序时,应该调用 persist 方法。

handleChange (event) {
event.persist();

this.setState(() => {
...
}
}

看看这个答案:

TypeError: evt.target is null in functional setState

关于reactjs - 在setState中使用函数返回对象和直接使用对象有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59845728/

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