【问题标题】:React-Navigation useIsFocused always returns true, and I can't figure out why?React-Navigation useIsFocused 总是返回 true,我不知道为什么?
【发布时间】:2020-08-17 00:21:47
【问题描述】:

我有一个非常简单的用例,基本上如果屏幕聚焦我希望这个函数运行,如果不是就不要运行。


  const isFocused = useIsFocused();

  const onViewRef = useRef(({ viewableItems }) => {

    if (!isFocused) return;

    //code to run
  });

特别是这个屏幕的堆栈:

const MyStack = () => {
  return (
    <Stack.Navigator headerMode="none">
      <Stack.Screen
        component={MyStackComponent}
        name="My"
      />
    </Stack.Navigator>
  );
};

这是在 tabNavigator 中使用的堆栈

     <Tab.Screen
        component={MyStack}
        name="My"
      />
      <Tab.Screen
          component={Other Stack}
          name="Other"
        />
      

所以基本上每当我转到我的应用程序上的任何其他选项卡时,使用 useIsFocused 挂钩的文件应该返回 false 对吗?因为现在无论如何它都会返回 true,而且我不能一直运行该函数。有什么指点吗?

【问题讨论】:

    标签: react-native react-hooks react-native-navigation


    【解决方案1】:

    为这个话题带来真正的答案。

    出于某种原因,在我的情况下,useIsFocused() 总是 return true; 从我第一次到达相关屏幕的那一刻起,直到我终止应用程序 (IOS)。

    所以我找到了另一个解决方案:使用 react-navigation 中的 navigation.isFocused() 方法。 (https://reactnavigation.org/docs/navigation-prop/#isfocused)

    而且效果很好! 希望对大家有所帮助

    这是我的例子:

    useEffect(() => {
            notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
                if (navigation.isFocused()) {
                    fetchConversationsList();
                }
            });
        }, [fetchConversationsList, navigation]);
    

    【讨论】:

      【解决方案2】:

      https://reactnavigation.org/docs/tab-based-navigation

      tabBarIcon: ({ focused, color, size })
      

      【讨论】:

      • 您可能希望edit 帖子包含比一行代码+一个链接更多的信息。请提及为什么这会有所帮助,例如用一两句话概括链接背后的内容
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 2012-04-03
      • 2021-09-11
      • 2015-05-12
      • 1970-01-01
      相关资源
      最近更新 更多