【问题标题】:How to cleanup useEffect in React Native while using React Navigation?使用 React Navigation 时如何清理 React Native 中的 useEffect?
【发布时间】:2021-03-17 14:58:23
【问题描述】:

我正在使用随机用户 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);
  }, []);

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

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

所以当我导航到详细信息页面时,useEffect 没有返回,这意味着组件没有卸载。实际上,由于堆栈导航,页面基本上位于每个页面的顶部并且仍在运行。那么在这种情况下如何停止我的区间函数呢?

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    react-navigation 文档中涵盖了这些场景。

    来自the docs

    React Navigation 向订阅的屏幕组件发出事件 他们。我们可以通过监听焦点和模糊事件来知道什么时候出现屏幕 分别进入焦点或失焦。

    例子:

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

    或者在useFocusEffect钩子的帮助下,上面的代码可以简化成这样。

    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 />;
    }
    

    【讨论】:

    • 这很酷,但是为什么我们需要 useCallback 钩子呢?
    • 根据docsNote: To avoid the running the effect too often, it's important to wrap the callback in useCallback before passing it to useFocusEffect as shown in the example.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 2021-10-31
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多