reactjs - 使用 Firebase 消息和 React Navigation(React Native,Android)在打开通知时导航到特定屏幕
问题描述
我有一个反应原生应用程序,它使用带有 firebase 消息传递和反应导航的远程通知。一切都很好,除了一段时间(或偶尔)通知侦听器不起作用。在我遇到任何问题之前可能需要长达 2 周的时间。这通常发生在应用程序已启动很长时间但未使用时,然后打开通知时,onNotificationOpenedApp
不运行,即我只看到索引屏幕。我正在使用“react-native-bootsplash”,如果这可能与它有关吗?
此外,有时一个旧的通知会触发一个监听器,我假设它getInitialNotification
被调用了两次(或多次)。android是否会半关闭一段时间未使用的应用程序,然后在应用程序再次打开时破坏侦听器?似乎该应用程序已部分卸载,然后出现问题。一旦问题发生,它很有可能会继续发生,直到我重新启动应用程序。
下面是注册监听器的代码:
getInitialNotification
当用户通过通知打开应用程序时,这将运行并返回通知。这是在getInitialUrl
传递给NavigationContainer
(react-navigation 组件)的道具中完成的,这是在他们的文档中推荐的
<NavigationContainer
ref={setNavigationRef}
linking={{
config: {
initialRouteName: 'SignedIn',
},
getInitialURL: async () => {
try {
// If app was opened with deeplink
const url = await Linking.getInitialURL();
if (url !== null) return url;
const notification = await messaging().getInitialNotification();
if (notification !== null) {
const {data} = notification;
if (data!.type === 'ARTICLE') {
return `${rootUrl}/site/news/${data!.id}`;
}
if (data!.type === 'TRANSFER') {
return `${rootUrl}/site/player/${data!.id}`;
}
}
return null;
} catch (error) {
return null;
}
},
}}>
<App />
</NotificationContainer>
在索引文件(App.tsx)中,我还注册了一个监听器,用于在应用程序已经启动但在后台打开通知时,使用onNotificationOpenedApp
onNotificationOpenedApp
:
useEffect(() => {
const unsubscribeOnNotificationOpenedApp =
messaging().onNotificationOpenedApp(remoteMessage => {
if (!remoteMessage.data) return;
const {type, id} = remoteMessage.data;
if (!id) return;
if (type === 'TRANSFER') {
loadPlayer(Number(id));
} else {
loadArticle(Number(id));
}
});
return unsubscribeOnNotificationOpenedApp;
}, [])
解决方案
推荐阅读
- java - 在日历视图事件中突出显示数据库中的列表数据
- javascript - 如何在不重新加载页面的情况下更新从 firestore 检索到的标记在我的地图上?
- reactjs - vscode 格式 reactnative 代码和 eslint 冲突
- javascript - React Native:错误:“无法读取未定义的属性'名称',”虽然包含名称的对象不是未定义的
- swift - 是否可以通过协议自定义 UINavigationBar?
- azure-devops - Azure 管道 yaml 权限被拒绝
- encryption - 将一个数字加密为特定字段中的另一个数字
- javascript - 如何在 reactjs 的不同组件中编写链接和路由
- directus - Directus 字段类型设置
- android - 使用 RxJava 改进视图模型的响应以在片段中观察