Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

reactjs - TypeError: evt.target is null in functional setState

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 });
}

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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

These are two different syntaxes for setState

First:

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

uses the updater function as the first argument.

Second:

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

uses the object to be updated

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

From the 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.

Your fist case would look like

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

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
    }));
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...