简体   繁体   English

React setInterval function 在重新渲染后继续在后台运行

[英]React setInterval function keeps running in the background after rerender

I am using setInterval inside useEffect with an empty dependency array inside one of my react component.我在 useEffect 中使用 setInterval,在我的一个反应组件中使用一个空的依赖数组。 There is true/false useState which controls the display of that component.有真/假 useState 控制该组件的显示。 When the state is false, the component is hidden and when it's true the component is shown.当 state 为假时,组件被隐藏,当它为真时,组件被显示。

Something like this:像这样的东西:

const [state, setState] = useState(false)

// in jsx render section

return (
   <div>
      {state? <component/> : '' }
   </div>
)

When the component loads for the first time the setInterval runs only one time which is what it supposes to do.当组件第一次加载时,setInterval 只运行一次,这是它应该做的。

If the state goes to false then back to true, the component is removed from the UI then displayed back again, but what happens here is now I have two setInterval functions running in the background, the first one doesn't shutdown.如果 state 变为 false 然后返回 true,则该组件将从 UI 中删除,然后再次显示回来,但是这里发生的是现在我有两个 setInterval 函数在后台运行,第一个没有关闭。

The number of the setInterval functions keeps increasing with each time that component rerender.每次组件重新渲染时,setInterval 函数的数量都会不断增加。

I don't understand how React works in this situation.我不明白 React 在这种情况下是如何工作的。

I need to know how it works and how to fix it.我需要知道它是如何工作的以及如何解决它。

This is the structure of React useEffect.React performs the cleanup when the component unmounts.这是 React useEffect 的结构。React 在组件卸载时执行清理。

useEffect(() => {
    //effect
    return () => {
        //cleanup runs on unmount
    }
}, [])

The cleanup function should have clearInterval() which will basically removes setInterval or stops it when component unmounts.清理 function 应该有 clearInterval() 这将基本上删除 setInterval 或在组件卸载时停止它。 See the practical code below:请参阅下面的实用代码:

let intervalid;
useEffect(
    () => {
     intervalid = setInterval(() => {console.log("Iterate");}, 1000));

      return function cleanup() {
        console.log("cleaning up");
        clearInterval(intervalid);
      };
    },
    []
  );

This above code is just for understanding approach.上面的代码只是为了理解方法。 Every effect may return a function that cleans up after it.每个效果都可能返回一个 function ,在它之后进行清理。 This lets us keep the logic for adding and removing subscriptions close to each other.这让我们可以保持添加和删除订阅的逻辑彼此接近。 # FROM REACT DOCS Reference # FROM REACT DOCS 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM