gpt4 book ai didi

reactjs - TypeError : evt. 目标在功能 setState 中为空

转载 作者:行者123 更新时间:2023-12-02 06:28:31 27 4
gpt4 key购买 nike

这两个函数之间的主要区别是什么?

handleOnChange(evt) {
this.setState(() => ({
tickerName: evt.target.value
}));
}

handleOnChange(evt) {
this.setState({ tickerName: evt.target.value });
}

为什么直接改变状态的 handleOnChange() 函数可以正常工作?

<input
type="text"
value={this.state.tickerName}
onChange={(evt) => this.handleOnChange(evt)}
/>

当我使用第一个通过回调更改状态的函数时,出现此错误:

TypeError: evt.target is null

最佳答案

setState 有两种不同的语法

首先:

handleOnChange(evt) {
this.setState(() => ({
tickerName: evt.target.value
}));
}

使用更新函数作为第一个参数。

第二个:

handleOnChange(evt) {
this.setState({ tickerName: evt.target.value });
}

使用要更新的对象

在更新函数中使用合成事件时需要使用event.persist()

来自 documentation :

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.

你的第一个案例看起来像

handleOnChange(evt) {
evt.persist();
this.setState(() => ({
tickerName: evt.target.value
}));
}

或者不使用 event.persist(),您可以将事件存储在另一个对象中

handleOnChange(evt) {
const value = evt.target.value;
this.setState(() => ({
tickerName: evt.target.value
}));
}

P.S. 仅当您希望根据 prevStateprops 更新当前状态时,才应使用 setState 的更新程序函数

CodeSandbox

关于reactjs - TypeError : evt. 目标在功能 setState 中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48075356/

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