TypeError:evt.target在函数setState中为null [英] TypeError: evt.target is null in functional setState

查看:130
本文介绍了TypeError:evt.target在函数setState中为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个功能之间的主要区别是什么?

What's the major difference bewteen these two functions?

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

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

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

And why with the handleOnChange() function that change the state directly this works fine?

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

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

When I use the first function that change the state with a callback I get this error:

TypeError: evt.target is null

推荐答案

这是setState的两种不同语法

These are two different syntaxes for setState

第一:

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

使用updater函数作为第一个参数.

uses the updater function as the first argument.

第二:

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

使用要更新的对象

在更新程序功能中使用综合事件时,需要使用event.persist()

When using the synthetic event in the updater function you need to use event.persist()

文档 :

SyntheticEvent被合并.这意味着SyntheticEvent对象 事件发生后将被重用,并且所有属性都将无效 回调已被调用.这是出于性能原因.因此, 您不能以异步方式访问事件.

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.

如果要以异步方式访问事件属性,则应在事件上调用event.persist(),这将删除 池中的合成事件,并允许对该事件的引用为 由用户代码保留.

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(),您可以将事件存储在另一个对象中

Or instead of using event.persist() you could store the event in another object

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

PS .仅当您希望基于prevStateprops

P.S. You should use the updater function for setState only when you wish to update the current state based on prevState or props

CodeSandbox

CodeSandbox

这篇关于TypeError:evt.target在函数setState中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆