问题描述
我有一个非常简单的用例,基本上,如果屏幕是聚焦的,我希望该功能运行,否则请运行。
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,而我不能一直运行该函数。有指针吗?
解决方法
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]);