[英]React Updater function doesn't work. Regular setState somehow does? (Cannot read property 'name' of null)
Today I learned about updater functions, and that it's better to use them, because of React 16's fibre core. 今天,我了解了更新程序功能,并且由于React 16的光纤核心,最好使用它们。
Here is the code that doesn't work: 这是无效的代码:
handleChange(e) {
this.setState((state, props) => ({
[e.target.name]: e.target.value
}));
}
And here is the code that DOES somehow work: 这是可以正常工作的代码:
handleChange(e) {
this.setState({[e.target.name]: e.target.value});
}
I did bind the function in the constructor like this: 我确实在构造函数中绑定了函数,如下所示:
this.handleChange = this.handleChange.bind(this);
And the input I call handleChange in looks like this: 我称之为handleChange的输入如下所示:
<input
className="todo-input"
type="text"
name="newTodo"
value={this.state.newTodo}
onChange={this.handleChange}
/>
For some reason, in the second version, React throws the following error: 出于某种原因,在第二个版本中,React引发以下错误:
Uncaught TypeError: Cannot read property 'name' of null
Can somebody explain to me please what's wrong with my code? 有人可以向我解释我的代码有什么问题吗?
PS: I learned about updater functions from this blogpost. PS:我了解到,从更新功能此博文。
Try use this: 试试这个:
handleChange(e) {
e.persist();
this.setState((state, props) => ({
[e.target.name]: e.target.value
}));
}
or this: 或这个:
handleChange(e) {
const value = e.target.value;
const name = e.target.name;
this.setState((state, props) => ({
[name]: value
}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.