我尝试过React的useEffect功能
useEffect(() => {
setInterval(() => {
const time =
Date.parse(untilDeadline.deadline) - Date.parse(new Date());
setuntilDeadline((prevValue) => {
return {
...prevValue,
seconds: Math.floor((time / 1000) % 60),
minutes: Math.floor((time / 1000 / 60) % 60),
hours: Math.floor((time / (1000 * 60 * 60)) % 24),
days: Math.floor(time / (1000 * 60 * 60 * 24)),
};
});
}, 1000);
}, []);
没有 [] 就崩溃了,到底为什么?
最佳答案
它崩溃的原因是因为你从未清理过 setInterval 调用。因此,每次组件重新渲染(例如通过 setuntilDeadline 调用),效果都会再次运行。 [] 表示该效果应该仅在挂载时运行,然后在卸载时自行清理(因为它是一个空的依赖项数组)。
此外,无论依赖项数组如何,您都应该清理 setInterval 调用,以确保不会出现内存泄漏和其他性能问题。
useEffect(() => {
const intervalId = setInterval(() => {
const time =
Date.parse(untilDeadline.deadline) - Date.parse(new Date());
setuntilDeadline((prevValue) => {
return {
...prevValue,
seconds: Math.floor((time / 1000) % 60),
minutes: Math.floor((time / 1000 / 60) % 60),
hours: Math.floor((time / (1000 * 60 * 60)) % 24),
days: Math.floor(time / (1000 * 60 * 60 * 24)),
};
});
}, 1000);
return ()=>{
clearInterval(intervalId);
}
}, []);
关于javascript - useEffect setInterval 和 setState 中的 Bug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61020496/