即使元素從頁面中刪除,js 程式碼也會繼續運作。
使用 react-js
編碼時的第一個困難。因為頁面沒有重新加載,所以初始腳本仍在運行,例如 setInterval、websocket、etc
程式碼。下面的簡單範例元素已被刪除但仍在運行。如果我必須使用全域變數創建,則無效
<button onclick="createNewJsCode()">create new js</button> <button onclick="removeJsCode()">remove js</button> <script> let id = '' function createNewJsCode(){ let s = document.createElement('script') let code = 'setInterval(`console.log(new Date())`,500)' s.id = (id = crypto.randomUUID()) s.appendChild(document.createTextNode(code)); document.body.appendChild(s); } function removeJsCode(){ document.getElementById(id).remove() } </script>
P粉3443557152024-02-18 12:15:34
你不能只刪除 <script>
節點,你必須做一些更具體的清理。
setInterval
傳回間隔 ID,您可以將其傳遞給 clearInterval
以停止它。
一般來說,我想說你的程式碼在 React 上下文中沒有多大意義,但在你的情況下,你可以這樣做:
sssccc
P粉0837850142024-02-18 10:00:45
這是一個 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); } }, []); returnThis is a page, and when unmounted will end the setInterval.} function OtherInfo() { return
Counter: {counter}, time: {new Date().toLocaleString()}
Check console you will also see console logging of datetime finishes.Notice how the timer stopped inside the console.} function App() { const [pageVis, setPageVis] = useState(true); return
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 &&} const root = ReactDOM.createRoot(document.querySelector('#mount')); root.render(} {!pageVis && }
{pageVis && } {!pageVis && });
sssccc sssccc