我得到以下错误

无法读取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>
        );
    }
}

当前回答

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

其他回答

你必须用'this'(默认对象)绑定你的方法。 不管你的函数是什么只要把它绑定到构造函数中。

constructor(props) {
    super(props);
    this.state = { checked:false };

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

handleChecked(){
    this.setState({
        checked: !(this.state.checked)
    })
}

render(){
    var msg;

    if(this.state.checked){
        msg = 'checked'
    }
    else{
        msg = 'not checked'
    }

    return (
        <div>               
            <input type='checkbox' defaultChecked = {this.state.checked} onChange = {this.handleChecked} />
            <h3>This is {msg}</h3>
        </div>
    );

如果任何人在使用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
      })
   })
}

ES5和ES6类之间有上下文差异。所以,实现之间也会有一点不同。

以下是ES5版本:

var Counter = React.createClass({
    getInitialState: function() { return { count : 1 }; },
    delta: function() {
        this.setState({
            count : this.state.count++
        });
    },
    render: function() {
        return (
            <div>
              <h1>{this.state.count}</h1>
              <button onClick={this.delta}>+</button>
            </div>
            );
    }
});

这是ES6版本:

class Counter extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count : 1 };
    }

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

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

注意,除了类实现中的语法差异之外,事件处理程序绑定也存在差异。

在ES5版本中,它是

              <button onClick={this.delta}>+</button>

在ES6版本中,它是:

              <button onClick={this.delta.bind(this)}>+</button>

如果使用内部axios,则在then中使用箭头(=>)

Axios.get ('abc.com').then((response) => {});

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

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

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

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

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