The js code will continue to run even if the element is removed from the page.
The first difficulty when coding with react-js
. Because the page is not reloaded, the initial scripts are still running, such as setInterval, websocket, etc
code. The simple example below has the elements removed but is still running. Doesn't work if I have to create using global variables
<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
You can't just delete the <script>
node, you have to do some more specific cleanup.
setInterval
Returns an interval ID that you can pass to clearInterval
to stop it.
Generally speaking, I'd say your code doesn't make much sense in a React context, but in your case you can do this:
sssccc
P粉0837850142024-02-18 10:00:45
This is a React question, here is an example of using setInterval
in a React component. If you use some form of React Router, the code below will also uninstall/install etc correctly.
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