[英]Start timer interval without using useEffect hooks
I want to start a timer interval in react native without using useEffect hook, in y case I want to start a timer when a promise resolves and change a state variable each second, how can I do this without using useEffect hook?我想在不使用 useEffect 钩子的情况下在 react native 中启动一个计时器间隔,在 y 的情况下,我想在承诺解析时启动一个计时器并每秒更改一个状态变量,如何在不使用 useEffect 钩子的情况下执行此操作?
i tried this:我试过这个:
useEffect(
() => {
const id = setInterval(() => {
setCounter(counter+1)
}, 1000);
return () => {
clearInterval(id);
};
},
[] // empty dependency array
);
And while it works I need to start the timer calling it from a normal function and not a hook.虽然它有效,但我需要启动计时器从正常函数而不是钩子调用它。
Any side effects (including starting a timer) should not belong to the main body of the component function.任何副作用(包括启动一个定时器)都不应该属于组件函数的主体。 Instead, it is best to delegate these things to a
useEffect()
hook.相反,最好将这些事情委托给
useEffect()
钩子。
If I understood your question correctly, you can still start that timer inside a hook, simply call the normal function inside.如果我正确理解了您的问题,您仍然可以在钩子中启动该计时器,只需调用内部的普通函数即可。
Eg it can be this simple if your normal function already returns a function to clean itself:例如,如果您的普通函数已经返回一个函数来清理自己,那么它可以是这么简单:
useEffect(() => startTimer(setCounterCallback), [])
Oh, and if the plan is to start it after a promise resolves, also wrap that async function inside the same useEffect()
:哦,如果计划是在 promise 解决后启动它,也可以将该异步函数包装在同一个
useEffect()
:
useEffect(() => {
const promise = Promise.resolve();
promise.then(() => startTimer(setCounterCallback));
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.