英文:
React Navigation - correct way to stop interval
问题
以下是您要翻译的内容:
"I'm fetching data every 5s in interval. I would want to stop fetching this data once I transition to another screen (using React Navigation).
What is the best way to do this. I'm using useFocusEffect and helper variable as you can see in the example below.
Is this the best practice or is there a better way to achieve it?
useEffect(() => {
const id = setInterval(() => {
fetchData();
}, isPlaying ? 5000 : null);
return () => clearInterval(id);
}, []);
useFocusEffect(
React.useCallback(() => {
setIsPlaying(true);
return () => setIsPlaying(false);
}, [])
);
"
希望这对您有所帮助。
英文:
I'm fetching data every 5s in interval. I would want to stop fetching this data once I transition to another screen (using React Navigation).
What is the best way to do this. I'm using useFocusEffect and helper variable as you can see in example below.
Is this the best practice or is there a better way to achieve it?
useEffect(() => {
const id = setInterval(() => {
fetchData();
}, isPlaying ? 5000 : null);
return () => clearInterval(id);
}, []);
useFocusEffect(
React.useCallback(() => {
setIsPlaying(true);
return () => setIsPlaying(false);
}, [])
);
答案1
得分: 2
这是一种处理内存泄漏并在播放更改时触发它的更常见方式,我曾经为一个类似的秒表应用程序做过类似的处理,代码如下:
useEffect(() => {
let id;
if (isPlaying) {
id = setInterval(() => {
fetchData()
}, 5000);
}
return () => {
clearInterval(id);
};
}, [isPlaying]);
英文:
This is a more common way to handle memory leaks and have it trigger when playing changes, I did something similar for a stopwatch app that looked like this:
useEffect(() => {
let id;
if (isPlaying) {
id = setInterval(() => {
fetchData()
}, 5000);
}
return () => {
clearInterval(id);
};
}, [isPlaying]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论