ReactJS: Warning: setState(…): Cannot update during an existing state transition

后端 未结 11 1116
一个人的身影
一个人的身影 2020-11-27 10:32

I am trying to refactor the following code from my render view:

11条回答
  •  春和景丽
    2020-11-27 10:45

    THE PROBLEM is here: onClick={this.handleButtonChange(false)}

    When you pass this.handleButtonChange(false) to onClick, you are actually calling the function with value = false and setting onClick to the function's return value, which is undefined. Also, calling this.handleButtonChange(false) then calls this.setState() which triggers a re-render, resulting in an infinite render loop.

    THE SOLUTION is to pass the function in a lambda: onClick={() => this.handleButtonChange(false)}. Here you are setting onClick to equal a function that will call handleButtonChange(false) when the button is clicked.

    The below example may help:

    function handleButtonChange(value){
      console.log("State updated!")
    }
    
    console.log(handleButtonChange(false))
    //output: State updated!
    //output: undefined
    
    console.log(() => handleButtonChange(false))
    //output: ()=>{handleButtonChange(false);}
    

提交回复
热议问题