问题描述
每当我点击 Expo 推送通知时,我都会尝试导航到某个屏幕。我想要导航到的屏幕位于 NavigationContainer
的深处。
但是,我现在面临的问题是,除了让应用自行重新启动之外,甚至无法导航到任何地方。我在真实设备上运行所有测试。
我正在使用 Expo 来处理这个学校项目。
我只在 SO 和 Expo 论坛(重复)中发现此 question 很有用。
这是我的应用程序导航结构:
-Navigation Structure-
AppNavigator
DrawerNavigator
MainNavigator
TabsNavigator
StackNavigator
StackNavigator
TabsNavigator
ScreenA (Want to navigate to)
ScreenB (Want to navigate to)
StackNavigator
ScreenA
ScreenB
StackNavigator
ScreenA
AuthNavigator
RegisterNavigator
ScreenA
创建了一个 useNotifications
钩子,我在 NavigationContainer
所在的主 App Navigator 中调用了它。
import React,{ useEffect } from 'react';
import * as Notifications from 'expo-notifications';
import navigation from '../navigation/RootNavigation';
const useNotifications = () => {
const notiResponseListener = React.createRef();
useEffect(() => {
notiResponseListener.current =
Notifications.addNotificationResponseReceivedListener(res => {
console.log(res.notification.request.content.data);
console.log('addNotificationResponseReceivedListener');
navigation.navigate(
('DrawerNavigator',{ screen: 'ChangePassword' }),{}
);
});
return () =>
Notifications.removeNotificationSubscription(notiResponseListener);
},[]);
};
export default useNotifications;
import { navigationRef } from '../navigation/RootNavigation';
import useNotifications from '../hooks/useNotifications';
const App = createStackNavigator();
const AppNavigator = () => {
useNotifications();
return (
<NavigationContainer ref={navigationRef}>
<App.Navigator headerMode='none'>
...
</App.Navigator>
</NavigationContainer>
);
};
最后,包含 NavigationContainer
中使用的 ref 的文件。
import React from 'react';
export const navigationRef = React.createRef();
const navigate = (name,params) => {
console.log('entered navigating'); // does not print
navigationRef.current?.navigate(name,params);
};
export default {
navigate
};
我已经搜索了高低,但我似乎无法找出问题所在。查看了 Expo 和 React Navigation 的文档,但我不确定发生了什么。这是我第一次处理推送通知和这样的案例。
感谢您的帮助,谢谢
解决方法
我们已经解决了使用 useLastNotificationResponse
的问题。
const [notification,setNotification] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();
//add this
const lastNotificationResponse =
Notifications.useLastNotificationResponse();
useEffect(() => {
if (lastNotificationResponse) {
//console.log(lastNotificationResponse);
//get the route
const route = JSON.stringify(
lastNotificationResponse.notification.request.content.data.route
);
//use some function to return the correct screen by route
getFullPath(JSON.parse(route));
}
},[lastNotificationResponse]);
根据您的路线,导航到正确的屏幕
getFullPath
:
import { navigationRef } from "./rootNavigation";
import routes from "./routes";
export function getFullPath(route) {
switch (route) {
case "HomeScreen":
return navigationRef.current?.navigate(routes.HOME);
case "Account":
return navigationRef.current?.navigate(routes.ACCOUNT,{
screen: routes.ACCOUNTSCREEN,});
default:
return;
}
}