我得到以下错误

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

当前回答

这个错误可以通过各种方法来解决

如果你使用的是ES5语法,那么根据React js文档你可以使用 必须使用绑定方法。 上面的例子是这样的: this.delta = this。delta。bind(this) 如果你使用的是ES6语法,那么你不需要使用bind方法,你可以 可以这样做: δ= ()= > { this.setState ({ Count: this.state.count++ }); }

其他回答

这个错误可以通过各种方法来解决

如果你使用的是ES5语法,那么根据React js文档你可以使用 必须使用绑定方法。 上面的例子是这样的: this.delta = this。delta。bind(this) 如果你使用的是ES6语法,那么你不需要使用bind方法,你可以 可以这样做: δ= ()= > { this.setState ({ Count: this.state.count++ }); }

你不需要绑定任何东西,只需要像这样使用箭头函数:

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

        this.state = {
            count: 1
        };

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

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

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

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

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

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

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

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

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

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