【发布时间】:2018-08-12 07:43:16
【问题描述】:
我正在尝试将pomodoro clock 作为 FreeCodeCamp 的练习项目。这是一个简单的时钟,只要当前计时器结束,它就会在您的会话时间和休息时间之间切换。
我在 react 中遇到了与 redux 相关的问题。这是我的应用启动时的状态。
当我单击减号或加号时,商店中的计时器和会话/休息时间将相应更新,但这并没有发生。会话/中断长度已更新,但计时器反映了先前的值。这是我增加会话时反映问题的屏幕截图
这是我负责的代码
updateSettings(type) {
if (!this.props.isPlaying) {
let isInvalid = false; // to show alert if user input is invalid
if (type === 'increase-session') {
this.props.increaseSession();
} else if (type === 'decrease-session') {
(this.props.session_length > 1) ? this.props.decreaseSession() : isInvalid = true;
} else if (type === 'increase-break') {
this.props.increaseBreak();
} else if (type === 'decrease-break') {
(this.props.break_length > 1) ? this.props.decreaseBreak() : isInvalid = true;
}
if (isInvalid) {
alert("Times less than 1 minutes is not allowed.");
} else {
this.props.setTimer({
minutes: this.props.session_length,
seconds: 0,
percentage: this.getTimeElapsedPercentage(this.props.session_length, 0)
});
}
}
}
在上面的代码中,所有动作都是同步的,当我调用this.props.increaseSession() 时,它会调度增加会话的动作。然后我调用this.props.timer(timerObj),而此计时器对象接收到 session_length 值但此 session_length 值未更新意味着增加(如果我增加会话)。
我的问题是所有操作都是同步的,那么为什么我在调度 setTimer() 时收到旧值。任何解决此问题的建议将不胜感激。
正如 Roy 所建议的,如果我在传递给 setTimer 之前自己更新了这些值,则百分比计算不正确。这是计算进度条(计时器周围的圆形条)的函数。该函数负责设置定时器启动时和每一秒的值。虽然它最初可以通过传递this.props.session_length 正确计算百分比,但这不会是正确的 session_length。会话长度也在产生问题的getTimeElapsedPercentage 内部使用。我可以使用一些逻辑来解决这个问题,但我希望有正确的解决方案而不是变通方法。
getTimeElapsedPercentage(minutes, seconds) {
let totalTimeInSec, timeElapsedInSec, timeRemainingInSec;
this.props.playType === 'break' ?
totalTimeInSec = this.props.break_length * 60 :
totalTimeInSec = this.props.session_length * 60;
timeRemainingInSec = minutes * 60 + seconds;
timeElapsedInSec = totalTimeInSec - timeRemainingInSec;
return timeElapsedInSec / totalTimeInSec * 100;
}
解决方案(解决方法 - 正确答案标记如下)
正如在 cmets 中与 Roy 讨论的那样,我知道道具只会在每次渲染后更新,因此当我使用 setTimer(timerObj) 设置计时器时,this.props.session_length 会为我提供以前的值。
所以我进入了这个解决方案。在第一次操作之后,我的 store 更新了,但 props 没有更新,所以我从我的 redux 代码中导入 store 并使用 store.getState() 来获取更新的值。我在我的setTimer(timerObj) 和getTimeElapsedPercentage 中使用了它来解决问题。
【问题讨论】: