setTimeout在React setState中 [英] setTimeout in react setState
问题描述
this.setState(prevState => ({
score: prevState.score + 10,
rightAnswers: prevState.rightAnswers + 1,
currentQuestion: setTimeout(() => {
prevState.currentQuestion + 1
}, 2000)
}))
}
在按钮上单击我更改状态".我的目标是延迟currentQuestion状态更改,在此期间我想显示某些状态消息,但我想立即更新分数.
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:此变体不起作用,它是我想要做的事情的整体表示.
PS: This variant doesn't work, it's for the overall representation of what I want to do.
谢谢.
推荐答案
您可以通过多种方式执行此操作:
You can do this multiple ways:
1)两次拨打setState
. React会将对setState
的所有并发调用批处理为一个批处理更新,因此这样的操作就很好了:
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)您可以在第一次通话结束后使用setState
回调更新状态 :
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);
});
这篇关于setTimeout在React setState中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!