React - uncaught TypeError: Cannot read property 'setState' of undefined

后端 未结 18 2381
清歌不尽
清歌不尽 2020-11-22 13:35

I am getting the following error

Uncaught TypeError: Cannot read property \'setState\' of undefined

even after binding delta in

18条回答
  •  失恋的感觉
    2020-11-22 14:29

    though this question had a solution already, I just want to share mine to make it be cleared, hope it could help:

    /* 
     * 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() {
       //....
       }
    }
    

提交回复
热议问题