Off*_*arc 2 react-native react-native-navigation react-hooks
我对此有非常简单的用例,基本上,如果屏幕聚焦,我希望该函数运行,如果没有,则不运行。
const isFocused = useIsFocused();
const onViewRef = useRef(({ viewableItems }) => {
if (!isFocused) return;
//code to run
});
Run Code Online (Sandbox Code Playgroud)
这是该屏幕的堆栈:
const MyStack = () => {
return (
<Stack.Navigator headerMode="none">
<Stack.Screen
component={MyStackComponent}
name="My"
/>
</Stack.Navigator>
);
};
Run Code Online (Sandbox Code Playgroud)
这是 tabNavigator 中使用的堆栈
<Tab.Screen
component={MyStack}
name="My"
/>
<Tab.Screen
component={Other Stack}
name="Other"
/>
Run Code Online (Sandbox Code Playgroud)
所以基本上每当我进入应用程序上的任何其他选项卡时,使用 useIsFocused 挂钩的文件都应该返回 false,对吧?因为现在无论如何它都会返回 true,而且我不能让该函数一直运行。有什么指点吗?
小智 11
为这个话题带来真正的答案。
出于某种原因,就我而言,useIsFocused()总是return true; from the moment I arrive on the screen in question for the first time untill I kill the app (IOS).
所以我找到了另一个解决方案:使用navigation.isFocused()react-navigation中的方法。(https://reactnavigation.org/docs/navigation-prop/#isfocused)
而且效果非常好!希望它能帮助别人
这是我的例子:
useEffect(() => {
notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
if (navigation.isFocused()) {
fetchConversationsList();
}
});
}, [fetchConversationsList, navigation]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10999 次 |
| 最近记录: |