我在调用回调函数时无法设置状态有麻烦。但是我不确定为什么下面的第二个选项比我尝试的第一个选项有效。我以为setState的回调函数。

function handleSendData() {

    console.log(this.state.experimentName)

}



//1st try was this.  Doesn't the callback in setState take a function, which I am giving it?

this.setState({
  testChoice: testChoice,
  experimentData: experimentData
}, this.handleSendData())


//2nd try works but I don't know why I have to give setState's callback a function inside of a function.

this.setState({
  testChoice: testChoice,
  experimentData: experimentData
}, () => {
  this.handleSendData()
})

最佳答案

在第一个示例中,您传入的是函数的结果,而不是实际函数本身。

因此它应该看起来像:

this.setState({
  testChoice: testChoice,
  experimentData: experimentData
}, this.handleSendData)

关于javascript - setState回调语法在这里有什么区别?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54466937/

10-13 05:10