简体   繁体   English

React Updater功能不起作用。 常规setState不知何故? (无法读取null的属性“名称”)

[英]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.

相关问题 React.JS-我正在尝试将功能从.js文件导入.jsx文件,但仍然无法正常工作。 无法读取null的属性“点击” - React.JS - I am trying to import functions from .js file into .jsx file, but it still doesn't work. Cannot read property 'click' of null' 无法读取null的属性“ setState” - Cannot read property 'setState' of null react 未捕获的类型错误:无法读取 null React 的属性“setState” - Uncaught TypeError: Cannot read property 'setState' of null React 使用React setState的更新器函数语法 - Updater function syntax with React setState 即使使用箭头函数,React 也无法读取 .then() 中未定义的属性 setState - React Cannot read property setState of undefined in .then() even using arrow function 单击按钮时无法读取null的属性“ setState” - Cannot read property 'setState' of null on button click TypeError:无法读取null的属性“setState” - TypeError: Cannot read property 'setState' of null 第一次没有读取 function 中的反应 setState - React setState inside function doesn't get read the first time componentdidmount不适用于split功能和setState在react中 - componentdidmount doesn't work with split function and setState in react 带有React的ES6,无法设置状态-&#39;无法读取未定义的属性&#39;setState&#39;? - ES6 with React, can't setState - 'Cannot read property 'setState' of undefined'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM