useEffect setInterval 和 setState 中的 Bug

1 javascript setinterval setstate reactjs

我尝试过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);
}, []);
Run Code Online (Sandbox Code Playgroud)

没有 [] 就崩溃了,到底为什么?

Zac*_*ber 5

它崩溃的原因是因为你从未清理过 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);
    }
}, []);
Run Code Online (Sandbox Code Playgroud)