gpt4 book ai didi

javascript - 从 React Hook useEffect 内部对 'timeInterval' 变量的赋值将在每次渲染后丢失

转载 作者:行者123 更新时间:2023-12-05 01:07:41 25 4
gpt4 key购买 nike

我需要每 6 秒自动重新渲染一次,我将组件定义如下。

const KioskPage = () => {

const [time, setTime] = useState(Date.now())

useEffect(() => {

timeInterval = setInterval(() => setTime(Date.now()), 60000)

return () => {
clearInterval(timeInterval)
}
}, [])
}

但我收到了通知:

Assignments to the 'timeInterval' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect react-hooks/exhaustive-deps

为什么会这样?以及如何解决这个问题?

问候

最佳答案

Assignments to the 'timeInterval' variable from inside React Hook useEffect will be lost after each render.

举例说明:

const KioskPage = () => {

const [time, setTime] = useState(Date.now())

let timeInterval;
// ^^^^^ this piece of code gets run on each render, when state/prop changes.
// this will, in practice, clear the `timeInterval` value set by your effect below, when the component re-renders after being mounted.

useEffect(() => {

timeInterval = setInterval(() => setTime(Date.now()), 60000)
// ^^^^ this assignment gets run once when the component mounts

return () => {
clearInterval(timeInterval)
}
}, []);

return (/* render something*/);
}

您可以按照建议通过“将此变量直接移动到 useEffect 中”来解决此问题。

const KioskPage = () => {
const [time, setTime] = useState(Date.now())

useEffect(() => {
const timeInterval = setInterval(() => setTime(Date.now()), 6000);
// ^^^^^^^^^^^^^^^

return () => {
console.log('clearing!');
clearInterval(timeInterval)
}
}, []);

const formatted = new Date(time).toLocaleTimeString();
return (
<h1>Time: {formatted}</h1>
);
}

关于javascript - 从 React Hook useEffect 内部对 'timeInterval' 变量的赋值将在每次渲染后丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67036279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com