react setState 中的 setTimeout

IT技术 javascript reactjs settimeout setstate timedelay
2021-04-26 08:01:29
this.setState(prevState => ({
    score:            prevState.score + 10,
    rightAnswers:     prevState.rightAnswers + 1,
    currentQuestion:  setTimeout(() => {
      prevState.currentQuestion + 1
    }, 2000)
    }))
  }

单击按钮时,我会更改状态。我的目标是延迟 currentQuestion 状态更改,在此期间我想显示某些状态消息,但我想立即更新分数而不会延迟。

这样做的正确方法是什么?

PS:这个变体不起作用,它是为了我想要做的事情的整体表现。

谢谢。

2个回答

您可以通过多种方式执行此操作:

1) 对 进行两次调用setStateReact 会将所有并发调用setState批处理为一个批处理更新,所以这样的事情非常好:

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

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

2)您可以第一次调用完成使用setState回调来更新状态

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

首先使用setState一些值更改分数和问题,null以便您知道它的更新,然后在此之后设置超时。

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>