简体   繁体   中英

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)

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). 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

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:

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 . Unless you think adding the extra babel configuration is worth your while you're probably best off sticking with binding in the constructor.

您应该使用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
    });
  }

  ...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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