React-Navigation useIsFocused 总是 returns true,我不明白为什么?

React-Navigation useIsFocused always returns true, and I can't figure out why?

我有一个非常简单的用例,基本上如果屏幕被聚焦,我希望这个功能 运行,如果没有,则不要 运行。


  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 挂钩的文件应该 return false 对吗?因为现在无论如何它 return 都是真的,而且我不能一直使用该功能 运行ning。有什么指点吗?

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

tabBarIcon: ({ focused, color, size })

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

出于某种原因,在我的情况下,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]);