javascript - (React) setState() callback not firing after state change - Stack Overflow

admin2025-04-19  0

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 ponent updates, but I am not seeing that behaviour in my ponent. 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()
  }

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 ponent updates, but I am not seeing that behaviour in my ponent. 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()
  }
Share asked Nov 27, 2017 at 17:24 trinhmatttrinhmatt 331 silver badge4 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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))
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745062431a282780.html

最新回复(0)