首页 > 解决方案 > 如何在 reactjs 中每 5 分钟后调度一个动作

问题描述

我试图每隔 5 分钟发送一次动作。一旦用户登录,它就必须调度动作。它将每 5 分钟后开始调度动作。我尝试使用setInterval,但这里的问题是即使我注销它也会继续调度操作。

这是我的代码我在我的 app.js 中定义了这个 keepAlive 函数,我将整个应用程序包装到 redux 商店中。这isAuthenticated是布尔函数。如果isAuthenticated为真并且仅API.getAcessToken在其中可用,localstorage那么我想调度操作。

  function keepAlive() {
    if (
      props.isAuthenticated === true &&
      API.getAccessTokenFromLocalStorage()
    ) {
      setInterval(() => {
        props.keepTokenAlive();
      }, 100000); // 1000ms =1sec
    } else {
      return null;
    }
  }
  keepAlive();

标签: javascriptreactjs

解决方案


你能做这个吗?

let to = null;

function keepAlive() {
    //Assign a reference to clear the interval
    to = setInterval(() => {
        if (
           props.isAuthenticated === true &&
           API.getAccessTokenFromLocalStorage()
        ) {
             props.keepTokenAlive();
        } else {
            // If not passing the condition, clear the interval
            clearInterval(to);
        }            
    }, 100000); // 1000ms =1sec
}

 keepAlive();
 

推荐阅读