如何在使用 React Navigation 时清理 React Native 中的 useEffect?

İlk*_*ker 3 reactjs react-native react-hooks

我正在使用随机用户 api 通过 setInterval 函数获取用户信息,我的 useEffect 如下所示;

// Users.js

useEffect(() => {
    const getUser = () => {
      fetch("https://randomuser.me/api")
        .then((res) => res.json())
        .then((data) =>
          setUsers((prevUsers) => {
            return setUsers([
              ...prevUsers,
              { key: data.results[0].login.uuid, value: data.results[0] },
            ]);
          })
        );

      console.log("cleanup?");
    };
    getUser();
    // const userInterval = setInterval(getUser, 5000);
    // return () => clearInterval(userInterval);
  }, []);

Run Code Online (Sandbox Code Playgroud)

我使用反应导航在另一个页面中显示每个用户的详细信息并像这样导航;

 <TouchableOpacity
 onPress={() => navigation.navigate("userDetails", item.value)}>

Run Code Online (Sandbox Code Playgroud)

因此,当我导航到详细信息页面时,useEffect 不会返回,这意味着组件不会卸载。实际上,由于堆栈导航,页面基本上位于每个页面之上并且仍在运行。那么在这种情况下我怎样才能停止我的间隔功能呢?

Mur*_*ati 6

这些场景包含在react-navigation 的文档中。

来自文档

React Navigation 向订阅它们的屏幕组件发出事件。我们可以监听焦点和模糊事件来分别了解屏幕何时进入焦点或失焦。

例子:

function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // Screen was focused
      // Do something
    });

    return unsubscribe;
  }, [navigation]);

  return <ProfileContent />;
}   
Run Code Online (Sandbox Code Playgroud)

或者借助useFocusEffecthook 上面的代码可以简化为这样。

import { useFocusEffect } from '@react-navigation/native';

function Profile() {
  useFocusEffect(
    React.useCallback(() => {
      // Do something when the screen is focused

      return () => {
        // Do something when the screen is unfocused
        // Useful for cleanup functions
      };
    }, [])
  );

  return <ProfileContent />;
}
Run Code Online (Sandbox Code Playgroud)

  • 根据[文档](https://reactnavigation.org/docs/use-focus-effect/),`注意:为了避免过于频繁地运行效果,在将回调传递给 useFocusEffect 之前将回调包装在 useCallback 中非常重要如示例所示。` (2认同)