我得到以下错误

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

当前回答

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

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

其他回答

在ES7+ (ES2016)中,您可以使用实验函数绑定语法操作符::来绑定。这是一种语法糖,和Davin Tryon的答案一样。

然后你可以重写this.delta = this.delta.bind(this);到this.delta =::this.delta;


对于ES6+ (ES2015),您还可以使用ES6+箭头函数(=>)来使用此功能。

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

为什么?来自Mozilla文档:

在箭头函数之前,每个新函数都定义了自己的this值[…]。对于面向对象风格的编程来说,这被证明是令人讨厌的。 箭头函数捕获封闭上下文的this值[…]

只需要更改bind语句 = > this.delta = this.delta.bind(this);

当在React中使用ES6代码时,总是使用箭头函数,因为这个上下文会自动与它绑定

用这个:

(videos) => {
    this.setState({ videos: videos });
    console.log(this.state.videos);
};

而不是:

function(videos) {
    this.setState({ videos: videos });
    console.log(this.state.videos);
};

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>

你还可以使用:

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

Or:

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

如果你正在传递一些参数..