刪除仍在運行的js程式碼
P粉864872812
P粉864872812 2024-02-17 18:08:32
0
2
452

即使元素從頁面中刪除,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粉864872812
P粉864872812

全部回覆(2)
P粉344355715

你不能只刪除 <script> 節點,你必須做一些更具體的清理。

setInterval 傳回間隔 ID,您可以將其傳遞給 clearInterval 以停止它。

一般來說,我想說你的程式碼在 React 上下文中沒有多大意義,但在你的情況下,你可以這樣做:



sssccc
P粉083785014

這是一個 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.
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
{pageVis && } {!pageVis && }
{pageVis && } {!pageVis && }
} const root = ReactDOM.createRoot(document.querySelector('#mount')); root.render();
sssccc
sssccc

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!