我得到以下错误

无法读取undefined的属性“setState”

即使在构造函数中绑定了delta。

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}

当前回答

箭头函数可以使您更容易避免绑定此关键字。像这样:

 delta = () => {
       this.setState({
           count : this.state.count++
      });
   }

其他回答

这是因为这个没有和这个绑定。

为了绑定,在构造函数中设置this.delta = this.delta.bind(this):

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

    this.delta = this.delta.bind(this);
}

目前,您正在调用bind。但是bind返回一个绑定函数。您需要将函数设置为其绑定值。

您需要将其绑定到构造函数,并记住对构造函数的更改需要重新启动服务器。否则,您将以相同的错误结束。

如果你使用的是ES5语法,那么你需要正确绑定它

this.delta = this.delta.bind(this)

如果你正在使用ES6及以上版本,你可以使用箭头函数,那么你不需要使用bind()它

delta = () => {
    // do something
  }

添加

onClick = {this.delta.bind ()}

就能解决问题。 当我们试图调用ES6类的函数时出现这个错误, 所以我们需要绑定这个方法。

如果任何人在使用axios或任何fetch或get时寻找相同的解决方案,并使用setState将返回此错误。

你需要做的是在外部定义组件,如下所示:

componentDidMount(){
  let currentComponent = this;
  axios.post(url, Qs.stringify(data))
     .then(function (response) {
          let data = response.data;
          currentComponent.setState({
             notifications : data.notifications
      })
   })
}