在间隔中使用状态时更新状态时出现问题



我正在构建一个React Native应用程序,并试图创建一个计时器。计时器使用setInterval在前台正常运行,并更新一个保持秒数并每1秒减少一次的状态。当应用程序备份时,会捕获并存储日期。当活动再次变为活动时,我试图计算两个日期之间的差异,然后更新状态以反映差异,这样用户就可以看到计时器在后台运行。

我遇到了一个问题,当计时器运行时,状态没有更新。

const home = () => {
const WORK_SECONDS = 1500; //1500
const SHORT_REST_SECONDS = 300; //300
const LONG_REST_SECONDS = 900; //900
const ACTIVE_COLOR = '#009688';
const PAUSED_COLOR = '#00695C';
const ADD_TIME = 60;
const NOTIFICATION_TITLE = "Time's up!";
const NOTIFICATION_BODY = "Finished!";
const [timer, setTimer] = useState({seconds: WORK_SECONDS, timeCap: WORK_SECONDS });
const [isActive, setIsActive] = useState(false);
const [timerColor, setTimerColor] = useState(ACTIVE_COLOR);
const [sessionCycle, setSessionCycle] = useState([]);
let time = 0;
const toggle = () => {
if (sessionCycle.length == 8) setSessionCycle([]);
setIsActive(!isActive);
setTimerColor((timerColor == ACTIVE_COLOR && timer.seconds != timer.timeCap) ? PAUSED_COLOR : ACTIVE_COLOR);
}
const reset = () => {
setTimer({...timer, seconds: timer.timeCap});
setIsActive(false);
}
useEffect(() => {
AppState.addEventListener('change', handleChange);  
return () => {
AppState.removeEventListener('change', handleChange);  
}
}, []);
const handleChange = (newState) => {
if (newState === "active") {
let resumeTime = moment(new Date());
let exitTime = moment(time);
let duration = moment.duration(resumeTime.diff(exitTime, 'seconds'));
let diff = duration.asSeconds() * 1000;
console.log("Attempting to substract - " + diff);
console.log(timer.seconds + " from appstate");
setTimer({...timer, seconds: timer.seconds - diff})
console.log(timer.seconds + " after subtraction");
}
else if (newState == "background") {
time = new Date();
}
}
useEffect(() => {
let interval = null;
if (isActive) {
if (timer.seconds == 0) {
//sendNotification(); 
// TODO: Add +1 to pomo total after finishing work session
updateSessionCycle("forward");  
clearInterval(interval);
toggle();
}
interval = setInterval(() => {
console.log(timer.seconds);
setTimer({...timer, seconds: timer.seconds - 1});
}, 1000);
} else if (!isActive && timer.seconds !== 0) {
clearInterval(interval);
} 
return () => clearInterval(interval);
}, [isActive, timer.seconds]);
const addTime = () => {
if (timer.seconds > timer.timeCap - 60) {
setTimer({...timer, seconds: timer.timeCap})
} else {
setTimer({...timer, seconds: timer.seconds + ADD_TIME});
}
}
return (
<View style={styles.chart}>
<ProgressCircle
percent={ (timer.seconds / timer.timeCap) * 100 }
radius={Math.ceil(Dimensions.get('window').height / 6)}
borderWidth={Math.ceil(Dimensions.get('window').height / 30)}
color={timerColor}
shadowColor="#212121"
bgColor="#303030"
>
<Text style={{ color: '#FFF', fontSize: 50 }}>{moment("2015-01-01").startOf('day').seconds(timer.seconds).format('m:ss')}</Text>
<Text style={{ color: '#9E9E9E', fontSize: 20 }}>{(timer.timeCap == WORK_SECONDS) ? "Work Session" : "Break"}</Text>
</ProgressCircle>
</View>
);
}

我怀疑您的问题是您可能在对setTimer的调用中使用了过时状态。在useEffect中,您正在创建一个setInterval函数,该函数在函数闭包中引用timer。每次调用setInterval函数时,都会得到相同的timer变量,因此调用:

setTimer({...timer, seconds: timer.seconds - 1});

将持续将seconds设置为比创建间隔时的timer.seconds值小1秒。

幸运的是,有一个简单的解决方法:

setTimer(timer => ({...timer, seconds: timer.seconds - 1}));

这将在每次执行更新之前获取最新的timer状态。

相关内容

  • 没有找到相关文章

最新更新