简体   繁体   English

在包含 useEffect 的组件上调用 API (React Native) 时,cleraInterval () 不起作用

[英]cleraInterval ()not working when on a component that contains useEffect to call the API (React Native)

how to stop setInterval on on the component that contains the APi call ??如何在包含 APi 调用的组件上停止 setInterval

example case案例

.....

useEffect(() => {
  getDataFromApi()
})


let count = 0;
let interval = setInterval(function(){

    // increasing the count by 1
    count += 1;

    // when count equals to 5, stop the function
    if(count === 5){
        clearInterval(interval);
    }

    // display count
    console.log(count);

}, 2000);

but in case program not stop when after five times但如果程序在五次后没有停止

if you are attempting to only run the effect once on mount, then you need to add the second param to the useEffect function to do that.如果您试图在挂载时只运行一次效果,那么您需要将第二个参数添加到useEffect function 来执行此操作。

// by putting this logic in the useEffect, you are creating a clousure that will prevent interval from being mutated on every render.
useEffect(() => {
  getDataFromApi()


  let count = 0;
  let interval = setInterval(function(){

  // increasing the count by 1
  count += 1;

  // when count equals to 5, stop the function
  if(count === 5){
    clearInterval(interval);
  }

  // display count
  console.log(count);

  }, 2000);
}, [])

the reason the code doesn't stop is because the component is mutating the reference to the original interval everytime the component rerenders.代码没有停止的原因是因为组件每次重新呈现时都会改变对原始interval的引用。 For this reason, you really shouldn't use a setInterval in a component render method.因此,您真的不应该在组件渲染方法中使用 setInterval。

you can achieve this by creating a interval variable first and clearActiveInterval function like this您可以通过先创建一个间隔变量和 clearActiveInterval function 来实现这一点

let count = 0;
let interval = null;

function clearActiveInterval() {
  clearInterval(interval);
}

rest of you code implementation would be like this rest 你的代码实现是这样的

interval = setInterval(function () {
  // increasing the count by 1
  count += 1;

  // when count equals to 5, stop the function
  if (count === 5) {
    clearActiveInterval();
  }

  // display count
  console.log(count);
}, 2000);

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

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