我得到以下错误

无法读取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语法,那么你需要正确绑定它

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

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

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

其他回答

添加

onClick = {this.delta.bind ()}

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

在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值[…]

检查状态 检查状态是否创建特定属性

这一点。状态= { 名称:", 电子邮件:”“ } 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) }

虽然这个问题已经有了答案,但我还是想分享一下我的答案,希望对大家有所帮助:

/* 
 * The root cause is method doesn't in the App's context 
 * so that it can't access other attributes of "this".
 * Below are few ways to define App's method property
 */
class App extends React.Component {
  constructor() {
     this.sayHi = 'hello';
     // create method inside constructor, context = this
     this.method = ()=> {  console.log(this.sayHi) };

     // bind method1 in constructor into context 'this'
     this.method1 = this.method.bind(this)
  }

  // method1 was defined here
  method1() {
      console.log(this.sayHi);
  }

  // create method property by arrow function. I recommend this.
  method2 = () => {
      console.log(this.sayHi);
  }
   render() {
   //....
   }
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>

    <script src="https://unpkg.com/react@0.14.8/dist/react.min.js"></script>
    <script src="https://unpkg.com/react-dom@0.14.8/dist/react-dom.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

  </head>
  <body>
  <div id="root"></div>
    <script type="text/babel">

        class App extends React.Component{

            constructor(props){
                super(props);
                this.state = {
                    counter : 0,
                    isToggle: false
                }
            this.onEventHandler = this.onEventHandler.bind(this);   
            }

            increment = ()=>{
                this.setState({counter:this.state.counter + 1});
            }

            decrement= ()=>{
                if(this.state.counter > 0 ){
                this.setState({counter:this.state.counter - 1});    
                }else{
                this.setState({counter:0});             
                }
            }
            // Either do it as onEventHandler = () => {} with binding with this  // object. 
            onEventHandler(){
                this.setState({isToggle:!this.state.isToggle})
                alert('Hello');
            }


            render(){
                return(
                    <div>
                        <button onClick={this.increment}> Increment </button>
                        <button onClick={this.decrement}> Decrement </button>
                        {this.state.counter}
                        <button onClick={this.onEventHandler}> {this.state.isToggle ? 'Hi':'Ajay'} </button>

                    </div>
                    )
            }
        }
        ReactDOM.render(
        <App/>,
        document.getElementById('root'),
      );
    </script>
  </body>
  </html>