简体   繁体   English

在反应中无法读取未定义的属性“ setState”

[英]In react Cannot read property 'setState' of undefined

My problem is when I try to write something in the input it gives me this error. 我的问题是,当我尝试在输入中写一些东西时,它给了我这个错误。 Can anyone help me? 谁能帮我? thx(I'm new on react btw) thx(我是React的新手)

class Searcher extends Component {
      constructor(props) {
        super(props)

        this.state = {
          inputValue: ''
        }
      }

      onChange (e) {
        console.log(e)
        this.setState({
          inputValue: e.target.value
        })
      }
      render () {
        return (
          <SearchBar>
           <SearchInput placeholder="Nunca pares de buscar" value={this.state.inputValue} onChange={this.onChange}/>
            <SearchContainer>
              <Search>
                <i className="fa fa-search" aria-hidden="true">
                </i>
              </Search>
            </SearchContainer>
          </SearchBar>
        )
      }
    }

Unlike createClass React doesn't autobind this for components (ES6 classes). createClass不同,React不会自动将其绑定this组件(ES6类)。 Therefore you have to bind the methods yourself. 因此,您必须自己绑定方法。 Up until now the most common approach is to bind the methods in the constructor: 到目前为止,最常见的方法是将方法绑定到构造函数中:

constructor(props) {
  super(props);
  this.state = { inputValue: '' };
  this.onChange = this.onChange.bind(this);
}

DEMO DEMO

It's best to do it here rather than in the render (as some code will show) because this way the bound function is only created once. 最好在此处而不是在渲染中进行操作(如一些代码所示),因为这样,绑定函数只能创建一次。 In a render it will be created with each new render which can be a performance problem 在渲染中,它将与每个新渲染一起创建,这可能是性能问题

More recently developers have been using an experimental feature of JavaScript called class properties which means that you can go without the constructor and use arrow functions to create the methods: 最近,开发人员一直在使用JavaScript的一种称为类属性的实验性功能,这意味着您可以不用构造函数而使用箭头函数来创建方法:

class Searcher extends Component {

  state = { inputValue: '' }

  onChange = (e) => {
    this.setState({
      inputValue: e.target.value
    });
  }

  ...

}

This, however, requires that you use babel to transform these new features during transpilation . 但是,这要求您在转译过程中使用babel转换这些新功能 Unless you think adding the extra babel configuration is worth your while you're probably best off sticking with binding in the constructor. 除非您认为添加额外的babel配置值得,否则您最好还是坚持在构造函数中进行绑定。

您应该使用this.onChange.bind(this) ,否则将不会引用Searcher类。

You can add one more dependency to solve the issue 您可以再添加一个依赖项来解决此问题

import autobind from 'autobind-decorator';

class Searcher extends Component {

  state = { inputValue: '' }

  @autobind
  onChange(e){
    this.setState({
      inputValue: e.target.value
    });
  }

  ...

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM