我得到以下错误

无法读取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.setState(() => ({ Comments: Comments //注释状态不可用 }))

2.检查(这个) 如果你在任何函数(即handleChange)中执行setState,检查函数是否绑定到这个函数或函数应该是箭头函数。

## 3种方法绑定到下面的函数##

//3 ways for binding this to the below function handleNameChange(e) { this.setState(() => ({ name })) } // 1.Bind while callling function onChange={this.handleNameChange.bind(this)} //2.make it as arrow function handleNameChange((e)=> { this.setState(() => ({ name })) }) //3.Bind in constuctor constructor(props) { super(props) this.state = { name: "", email: "" } this.handleNameChange = this.handleNameChange.bind(this) }

其他回答

添加

onClick = {this.delta.bind ()}

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

你必须用这个关键字绑定新事件,正如我下面提到的…

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

        this.state = {
            count : 1
        };

        this.delta = 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.setState(() => ({ Comments: Comments //注释状态不可用 }))

2.检查(这个) 如果你在任何函数(即handleChange)中执行setState,检查函数是否绑定到这个函数或函数应该是箭头函数。

## 3种方法绑定到下面的函数##

//3 ways for binding this to the below function handleNameChange(e) { this.setState(() => ({ name })) } // 1.Bind while callling function onChange={this.handleNameChange.bind(this)} //2.make it as arrow function handleNameChange((e)=> { this.setState(() => ({ name })) }) //3.Bind in constuctor constructor(props) { super(props) this.state = { name: "", email: "" } this.handleNameChange = this.handleNameChange.bind(this) }

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

你还可以使用:

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

Or:

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

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