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

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

    1. Check state check state whether you create particular property or not

    this.state = {
                name: "",
                email: ""
                }
                
               
                
    this.setState(() => ({ 
                 comments: comments          //comments not available in state
                 })) 

    2.Check the (this) if you doing setState inside any function (i.e handleChange) check whether the function bind to this or the function should be arrow function .

    ## 3 ways for binding this to the below function##

    //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)
            }

提交回复
热议问题