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

后端 未结 18 2341
清歌不尽
清歌不尽 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:22

    There are two solutions of this issue:

    The first solution is add a constructor to your component and bind your function like bellow:

    constructor(props) {
            super(props);
    
            ...
    
            this.delta = this.delta.bind(this);
        }
    

    So do this:

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

    Instead of this:

    this.delta.bind(this);
    

    The second solution is to use an arrow function instead:

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

    Actually arrow function DOES NOT bind it’s own this. Arrow Functions lexically bind their context so this actually refers to the originating context.

    For more information about bind function:

    Bind function Understanding JavaScript Bind ()

    For more information about arrow function:

    Javascript ES6 — Arrow Functions and Lexical this

提交回复
热议问题