[英]Cleaning Function not Working in UseEffect Hook During Component Unmount in React Native
In react native app, there are two components A
and B
in App.js
which toggle with k
state change.在
App.js
Native 应用程序中, App.js
有两个组件A
和B
,它们会随着k
状态变化而切换。
App.js
...
const App = () => {
const [ k, setK ] = useState(false);
const toggleK = () => setK(!k);
if(k) {
return <A />;
}else {
return <B toggleK={toggleK} />;
}
};
...
In A
, setInterval
is initialized in useffect
.在
A
, setInterval
在useffect
初始化。 It calls async function every 10 seconds.它每 10 秒调用一次异步函数。 But when it unmounts on
K
state change in App.js
, the cleaning function is not run (no A unmounting...
is logged) and so does the clearInterval
.但是当它卸载
App.js
K
状态更改时,不会运行清理功能(没有记录A unmounting...
), clearInterval
也是如此。
Any thing I'm doing wrong here?我在这里做错了什么?
...
const A = () => {
const [ someState, setSomeState ] = useState(...);
let timer;
useEffect(() => {
if(!timer) {
timer = setInterval(async () => await run_async_func(), 10000);
}
return () => {
console.log('A unmounting...');
clearInterval(timer);
};
}, [ someState ]);
};
...
Try this with useRef().用 useRef() 试试这个。
const A = () => {
const timer = useRef()
const [ someState, setSomeState ] = useState(...);
useEffect(() => {
if(!timer) {
timer.current = setInterval(async () => await run_async_func(), 10000);
}
return () => {
console.log('A unmounting...');
clearInterval(timer.current);
};
}, [ someState ]);
};
Resolved the issue解决了问题
A. Overlooked the someState
in useEffect
dependency array. A.忽略了
someState
在useEffect
依赖性阵列。 Basically, cleaner function will only run if any variable in dependency array mutates.基本上,只有在依赖数组中的任何变量发生变异时,更清洁的函数才会运行。 So, I used another
useEffect
without any dependencies (see below).所以,我使用了另一个没有任何依赖关系的
useEffect
(见下文)。 Thanks @TayyabMazhar for pointing out this感谢@TayyabMazhar 指出这一点
...
const A = () => {
const [ someState, setSomeState ] = useState(...);
let timer;
useEffect(() => {
if(!timer) {
timer = setInterval(async () => await run_async_func(), 10000);
}
}, [ someState ]);
useEffect(() => {
return () => {
console.log('A unmounting...');
clearInterval(timer);
};
}, []);
};
...
you can use this hook i create this one你可以使用这个钩子我创造了这个
import { useEffect, useRef } from 'react';
export const useInterval = (callback: () => void, delay: number): void => {
const savedCallback = useRef(null);
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.