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
}

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();
添加回答
举报