为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 reactjs 中每 5 分钟发送一次动作

如何在 reactjs 中每 5 分钟发送一次动作

芜湖不芜 2023-05-18 10:08:46
我试图每 5 分钟发送一次动作。一旦用户登录,它就必须调度操作。它将在每 5 分钟后开始调度操作。我尝试使用setInterval,但这里的问题是即使我注销它也会继续执行调度操作。这是我的代码,我在我的 app.js 中定义了这个 keepAlive 函数,我将整个应用程序包装到 redux store 中。这是isAuthenticated布尔函数。如果isAuthenticated是 true 并且只有在我想派遣行动时才API.getAcessToken可用。localstorage  function keepAlive() {    if (      props.isAuthenticated === true &&      API.getAccessTokenFromLocalStorage()    ) {      setInterval(() => {        props.keepTokenAlive();      }, 100000); // 1000ms =1sec    } else {      return null;    }  }  keepAlive();
查看完整描述

2 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

您可以创建自定义 React 挂钩。有一些库可以解决这个问题,但涉及的代码很少,您可以自己解决。

例如,这是来自use-interval NPM 包的源代码:

import { useEffect, useRef } from 'react';


const useInterval = (callback, delay) => {

  const savedCallback = useRef();


  useEffect(

    () => {

      savedCallback.current = callback;

    },

    [callback]

  );


  useEffect(

    () => {

      const handler = (...args) => savedCallback.current(...args);


      if (delay !== null) {

        const id = setInterval(handler, delay);

        return () => clearInterval(id);

      }

    },

    [delay]

  );

};


export default useInterval;

你会像这样使用它:


const MyComponent = () => {

  useInterval(() => {

    // your code here

  }, 5000);


  return null

}


查看完整回答
反对 回复 2023-05-18
?
SMILET

TA贡献1796条经验 获得超4个赞

你能做这个吗?


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();


查看完整回答
反对 回复 2023-05-18
  • 2 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信