React Navigation – 停止定时器的正确方法

huangapple go评论53阅读模式
英文:

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]);

huangapple
  • 本文由 发表于 2023年2月9日 01:07:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定