setTimeout in react setState

两盒软妹~` 提交于 2020-03-21 04:36:32

问题


this.setState(prevState => ({
    score:            prevState.score + 10,
    rightAnswers:     prevState.rightAnswers + 1,
    currentQuestion:  setTimeout(() => {
      prevState.currentQuestion + 1
    }, 2000)
    }))
  }

On button click I change the state. My goal is to have a delay in currentQuestion state change, during which I want to show certain status messages, yet I want to update the score right away without delays.

What's the proper way to do that?

PS: This variant doesn't work, it's for the overall representation of what I want to do.

Thanks.


回答1:


You can do this multiple ways:

1) Make two calls to setState. React will batch any concurrent calls to setState into one batch update, so something like this is perfectly fine:

this.setState( prevState => ({
  score: prevState.score + 10,
  rightAnswers: prevState.rightAnswers + 1
}));

setTimeout( () => {
  this.setState( prevState => ({
    currentQuestion: prevState.currentQuestion + 1
  }));
}, 2000);

2) You can use the setState callback to update state after your first call is finished:

this.setState(prevState => ({
  score:            prevState.score + 10,
  rightAnswers:     prevState.rightAnswers + 1
}), () => {
  setTimeout( () => {
      this.setState( prevState => ({
      currentQuestion: prevState.currentQuestion + 1
    }));
  }, 2000);
});



回答2:


First use setState to change score and question with some value like null so that you know its updating and then also set timeout after that.

class Example extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      score: 1,
      question: "A"
    }
  }

  update() {
    this.setState(prev => ({
      score: prev.score + 1,
      question: null
    }));

    this.change = setTimeout(() => {
      this.setState({question: "B"})
    }, 2000)
  }

  render() {
    let {score, question} = this.state;
    let style = {border: "1px solid black"}
	
    return (
      <div style={style} onClick={this.update.bind(this)}>
        <div>{score}</div>
        <div>{question ? question : "Loading..."}</div>
      </div>
    )
  }
}

ReactDOM.render( < Example / > , document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


来源:https://stackoverflow.com/questions/51026090/settimeout-in-react-setstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!