React form onChange->setState one step behind

前端 未结 7 1562
南方客
南方客 2020-12-02 12:21

I encountered this problem building a webapp and I replicated it in this jsfiddle. Essentially, I would like an input to call this.setState({message: input_val})

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 12:49

    I was pulling my hair out for like an hour because of this so I decided to share... If your callback is still one step behind and seemingly not working, ensure you don't CALL the function with parenthesis... Just pass it in. Rookie mistake.

    RIGHT:

    handleChange: function(e) {
        console.log(e.target.value);
        this.setState({message: e.target.value}, this.handleSubmit);
    }
    

    VS

    WRONG:

    handleChange: function(e) {
        console.log(e.target.value);
        this.setState({message: e.target.value}, this.handleSubmit());
    }
    

提交回复
热议问题