setState的回调是否在设置(同步)状态后发生?

时间:2019-04-05 06:08:24

标签: javascript reactjs

我有一个带有“ change”和“ cancel”值的表格选择。 每次选择其他选项时,都会console.log记录“ mySelection”的值

handleSelectChange = e => {
    var myValue = e.target.value
    if (myValue == "change"){
        this.setState({selectText: "Change rent date"})
        this.setState({selection: "sdsd"})
        this.setState({mySelection: "change" }, console.log(this.state.mySelection))
    }
    if (myValue == "cancel"){
        this.setState({selectText: "Cancel a rent"})
        this.setState({selection: "bob"})
        this.setState({mySelection: "cancel"  }, console.log(this.state.mySelection))
    }
}

当我选择更改时,控制台日志取消。.当我选择取消时,控制台日志更改。我以为setState的回调发生在设置状态之后?

谢谢

1 个答案:

答案 0 :(得分:3)

您必须将函数作为handleSelectChange = e => { var myValue = e.target.value if (myValue == "change"){ this.setState({selectText: "Change rent date"}) this.setState({selection: "sdsd"}) this.setState({mySelection: "change" }, () => console.log(this.state.mySelection)) } if (myValue == "cancel"){ this.setState({selectText: "Cancel a rent"}) this.setState({selection: "bob"}) this.setState({mySelection: "cancel" }, () => console.log(this.state.mySelection)) } } 的第二个参数传递

xenian13.kat