这是我的反应代码。它使组件无限重新渲染:
const [seconds, setSeconds] = useState(60)
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds - 1);
}, 1000);
return () => clearInterval(interval);
}, []);
console.log("object"); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
发生这种情况是因为您仅在组件卸载时清除间隔,这仅在用户离开页面时才会发生。
也许这就是您所需要的?当间隔达到 0 时,我将清除它。但是为此我必须使用引用,我不能使用 setInterval 中的状态,因为它只有初始值:
export default function App() { const [seconds, setSeconds] = useState(5); const secondsRef = useRef(seconds); useEffect(() => { const interval = setInterval(() => { if (secondsRef.current seconds - 1); }, 1000); return () => clearInterval(interval); }, []); console.log("running", new Date()); return{seconds ; }