React form onChange->setState one step behind

前端 未结 7 1550
南方客
南方客 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:38

    There is a much simpler way to do this, setState(updater, callback) is an async function and it takes the callback as second argument,

    Simply pass the handleSubmit as a callback to setState method, this way after setState is complete only handleSubmit will get executed.

    For eg.

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

    Try to change the handleChange() method like above and it will work.

    for syntax of using setState check this link

提交回复
热议问题