简体   繁体   English

(反应)setState()回调在状态更改后不触发

[英](React) setState() callback not firing after state change

I am using React for this project. 我正在为这个项目使用React。

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. 使用devtools可以看到状态确实发生了变化,所以这不是问题。 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. 您没有将函数传递给setState回调,而是对其进行了调用。 You can pass a function and parameter using bind function like this 您可以像这样使用bind函数传递函数和参数

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

The other way is to use a closure . 另一种方法是使用closure You can make simulateClick function to return a function like this 您可以使simulateClick函数返回类似这样的函数

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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