Javascript 这里setState回调语法的区别是什么?

Javascript 这里setState回调语法的区别是什么?,javascript,reactjs,Javascript,Reactjs,在调用回调函数时,我遇到了状态未设置的问题。但我不确定为什么下面的第二个选项有效,而不是我尝试的第一个。我以为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.se

在调用回调函数时,我遇到了状态未设置的问题。但我不确定为什么下面的第二个选项有效,而不是我尝试的第一个。我以为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)


第一次尝试时,立即调用
this.handleSendData
,并将返回值赋给
setState
。正确的方法是删除
()
,然后将函数作为引用传递,以便在设置状态时调用

应该是

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

您的问题是认为
this.handleSendData()
是一个函数,而它不是,它是函数执行的结果

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()
})

比如说

function sum(){
    return 2 + 2;
}
sum()
4
不是函数,是函数的结果,函数是
sum

因此,基本上您可以执行以下操作:

1) 发送匿名函数,就像您在2dn try中所做的那样

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

2) 发送函数而不是执行它:

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


在第一个示例中,
立即调用this.handleSendData()

const fn=callback=>{
console.log('in Fn');
回调();
}
常量handleSendData=a=>{
console.log('in handleSendData')
}
fn(handleSendData())

//请注意,在Fn之前记录的handleSendData中,下面所有的回答都是正确的和有用的,但这一个让我感到很高兴…谢谢