Reactjs 反应本机,状态不';由于批处理更新,无法按预期进行更改,但我该怎么办?
我很难更新显示给用户的消息字符串。解决这个问题的最好办法是什么 单击start pomodoro(第23行的函数)应该会显示“哇,这么忙!做得好,继续前进!”,这很好。然后,当我点击暂停按钮时,它正确地显示“冻结”(第75行的功能),但是如果我点击resume Pomotoro按钮,而不是“Busy Busy!Keep going!”应用程序将文本保留为“冻结”,因此第80行的设置状态不会及时触发。。。我如何让它工作? 我尝试使用componentDidUpdate(),它可以工作,但代码看起来很糟糕,令人困惑,如果我想添加更多消息怎么办?它会变得如此混乱Reactjs 反应本机,状态不';由于批处理更新,无法按预期进行更改,但我该怎么办?,reactjs,react-native,Reactjs,React Native,我很难更新显示给用户的消息字符串。解决这个问题的最好办法是什么 单击start pomodoro(第23行的函数)应该会显示“哇,这么忙!做得好,继续前进!”,这很好。然后,当我点击暂停按钮时,它正确地显示“冻结”(第75行的功能),但是如果我点击resume Pomotoro按钮,而不是“Busy Busy!Keep going!”应用程序将文本保留为“冻结”,因此第80行的设置状态不会及时触发。。。我如何让它工作? 我尝试使用componentDidUpdate(),它可以工作,但代码看起来
componentDidUpdate(prevProps, prevState) {
if (this.state.activeTimerType != prevState.activeTimerType) {
if (this.state.activeTimerType === timerType.busyTimer && prevState.activeTimerType != timerType.paused) {
this.setState({message:'wow, so much busy! Great work, keep on going!'})
} if (this.state.activeTimerType === timerType.busyTimer && prevState.activeTimerType === timerType.paused) {
this.setState({message: 'Busy busy busy! Keep on going!'})
} else if (this.state.activeTimerType === timerType.breakTimer && prevState.activeTimerType === timerType.paused) {
this.setState({message: 'A break after a break? Much smart, wow!'})
}
}
}
我还看到了有关component.forceUpdate()的内容,但我不知道如何使用它。将其添加到第83行不会改变任何事情
togglePomodoroPause() {
// resume timer, if pomodoro was paused
if (this.state.activeTimerType === timerType.paused) {
this.interval = setInterval(this.incrementTimer, 1000)
console.log(this.state.activeTimerType)
this.setState({
activeTimerType: this.prevTimerType,
})
this.forceUpdate()
我通过在setState中使用回调解决了这个问题,如下所示:
this.setState({
activeTimerType: this.prevTimerType,
}, function() {
if (this.state.activeTimerType === timerType.busyTimer) {
this.setState({message: 'Busy busy busy! Keep on going!'})
} else if (this.state.activeTimerType === timerType.breakTimer) {
this.setState({message: 'A break after a break? Much smart, wow!'})
}
})