简体   繁体   中英

(React) setState() callback not firing after state change

I am using React for this project.

I need to read the state directly after I set it (using the callback), but when I print the state to the screen using the callback I get the values of the previous state. Using devtools I can see that the state does change, so that is not the problem. I looked at the docs and it said the callback is supposed to fire after the state is changed and the component updates, but I am not seeing that behaviour in my component. I am also not getting any error messages.

Here is the code, thanks for your help!

onAnswerSelect = (e) => {
    const selectedAnswer = e.target.value;
    //Set the state, then simulate a click on the submit button
    this.setState(() => ({selectedAnswer}), this.simulateClick(e))
  }

simulateClick = (e) => {
    console.log(this.state.selectedAnswer)
    e.target.parentNode.parentNode.firstChild.click()
  }

You are not passing function to setState callback but calling it. You can pass a function and parameter using bind function like this

this.setState(() => ({selectedAnswer}), this.simulateClick.bind(this,e))

The other way is to use a closure . You can make simulateClick function to return a function like this

simulateClick = (e) => () => {
    console.log(this.state.selectedAnswer)
    e.target.parentNode.parentNode.firstChild.click()
  }

this.setState(() => ({selectedAnswer}), this.simulateClick(e))

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