這是我的反應(yīng)代碼。它使組件無限重新渲染:
const [seconds, setSeconds] = useState(60) useEffect(() => { const interval = setInterval(() => { setSeconds(seconds => seconds - 1); }, 1000); return () => clearInterval(interval); }, []); console.log("object");
發(fā)生這種情況是因為您僅在組件卸載時清除間隔,這僅在用戶離開頁面時才會發(fā)生。
也許這就是您所需要的?當(dāng)間隔達(dá)到 0 時,我將清除它。但是為此我必須使用引用,我不能使用 setInterval 中的狀態(tài),因為它只有初始值:
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 ; }