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

我试图每 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();


芜湖不芜
浏览 162回答 2
2回答

四季花海

您可以创建自定义 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}

SMILET

你能做这个吗?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();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript