在react中无法读取未定义的属性'setState'

问题描述 投票:0回答:3

我的问题是,当我尝试在输入中写一些东西时,它给了我这个错误。谁能帮我? thx(我是新的反应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>
        )
      }
    }
javascript reactjs
3个回答
1
投票

createClass不同,React不会为组件自动提取this(ES6类)。因此,您必须自己绑定方法。到目前为止,最常见的方法是绑定构造函数中的方法:

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

DEMO

最好在这里而不是在渲染中(如某些代码所示),因为这样绑定函数只创建一次。在渲染中,它将使用每个新渲染创建,这可能是性能问题

最近开发人员一直在使用JavaScript的实验性功能,称为类属性,这意味着您可以在没有构造函数的情况下使用箭头函数来创建方法:

class Searcher extends Component {

  state = { inputValue: '' }

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

  ...

}

但是,这需要您使用babel to transform these new features during transpilation。除非你认为添加额外的babel配置是值得的,你可能最好在构造函数中坚持使用绑定。


0
投票

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


0
投票

您可以添加一个依赖项来解决问题

import autobind from 'autobind-decorator';

class Searcher extends Component {

  state = { inputValue: '' }

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

  ...

}
© www.soinside.com 2019 - 2024. All rights reserved.