This is a page, and when unmounted will end the setInterval. Counter: {counter}, time: {new Date().toLocaleString()} Check console you will also see console logging of datetime finishes.
}
function OtherInfo() {
return
Notice how the timer stopped inside the console. If you click Show Page the component will be mounted again, this is kind of the basis of how React Router works in a Single Page Application (SPA).
}
function App() {
const [pageVis, setPageVis] = useState(true);
return
你不能仅仅删除
<script>节点,你必须做一些更具体的清理。setInterval返回一个间隔 ID,您可以将其传递给clearInterval以停止它。一般来说,我想说你的代码在 React 上下文中没有多大意义,但在你的情况下,你可以这样做:
这是一个 React 问题,下面是在 React 组件中使用
setInterval的示例。如果您使用某种形式的 React Router,下面的代码也将正确卸载/安装等。const {useState, useEffect} = React; function Page() { const [counter, setCounter] = useState(0); useEffect(() => { const i = setInterval(() => { console.log(new Date()); setCounter(c => c +1); }, 1000); return () => { console.log('umount'); clearInterval(i); } }, []); return
This is a page, and when unmounted will end the setInterval.
}
function OtherInfo() {
return
Notice how the timer stopped inside the console.
}
function App() {
const [pageVis, setPageVis] = useState(true);
return
{pageVis && }
{!pageVis && }
}
const root = ReactDOM.createRoot(document.querySelector('#mount'));
root.render( );Counter: {counter}, time: {new Date().toLocaleString()}
Check console you will also see console logging of datetime finishes.
If you click Show Page the component will be mounted again, this is kind of the basis of how React Router works in a Single Page Application (SPA).
{pageVis && } {!pageVis && }