简体   繁体   中英

What is the difference in setState callback syntax here?

I was having trouble with the state not being set by the time the callback function was called. But I am unsure why the 2nd option below worked rather the first one I tried. I thought setState's callback took a function.

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

In your first example, you are passing in the result of a function, not the actual function itself.

so it should look like:

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

In your first try you immediately call the this.handleSendData and give the return value to the setState . The correct way would be to remove the () and so pass the function as a reference to be called when the state is set.

It should be

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

your problem is thinking that this.handleSendData() is a function, and it is not, it is the result of the execution of a function.

for example

function sum(){
    return 2 + 2;
}

sum() is 4 which is not a function, is the result of the function, the function is sum

so basically you can do the following:

1) send the anonymous function as you did on your 2dn try.

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

2) send the function instead of executing it:

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

in the first example, this.handleSendData() gets called immediately :

 const fn = callback => { console.log('in Fn'); callback(); } const handleSendData = a => { console.log('in handleSendData') } fn(handleSendData()) // notice in handleSendData logged before Fn 

when you pass the reference like handleSendData , it gets aclled inside fn()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM