在react-native-firebase/messaging的onMessage()方法中使用Context Provider有问题吗?

问题描述 投票:0回答:1

作为开发者世界的新人,目前正在从事 React Native Expo 项目,我第一次寻求您的帮助。

我们在应用程序中收到 FCM 通知;我们想用 Toast 来显示这些通知。但是,如果用户已经在正确的页面上并且可以看到界面更新,我们如何防止显示Toast呢? FCM 的“onMessage”回调是否无法访问上下文提供程序?

我的目标是防止用户在某个页面(在本例中为对话)上时出现通知。使用的包是react-native-firebase(用于后端和接收)和Notifee用于显示通知。 我遇到的问题是,当在对话中发布新消息时,即使用户当时在页面上,也会收到通知。

因此,我需要确定用户位于哪个页面并保存它。 我提出了使用页面名称与现有提供程序中的对话 ID 相连接的想法,以了解何时推送通知。

问题是,在firebase/messaging的messaging().onMessage()方法中,Context似乎无法被识别,并且总是显示为空。

相关代码如下:

useEffect(() => {
   const {currentPage} = useContext(DataContext);
   console.log('current page on HomeScreen', currentPage);
    ...

    if (!isExpoGo) {
      if (requestUserPermission()) {
        messaging().getToken().then((token) => {
          sendPushToken(token, user);
        });
      } else {
        console.log('Messaging: failed token status');
      }

      // Assume a message-notification contains a "type" property in the data payload of the screen to open
      messaging().onNotificationOpenedApp((remoteMessage) => {
        console.log(
          'Notification caused app to open from background state:',
          remoteMessage.notification,
        );
        // navigation.navigate(remoteMessage.data.type);
        console.log('App should navigate : ', remoteMessage.data);
      });

      // Check whether an initial notification is available
      messaging()
        .getInitialNotification()
        .then((remoteMessage) => {
          if (remoteMessage) {
            console.log(
              'Notification caused app to open from quit state:',
              remoteMessage.notification,
            );
            console.log('App woke up : ', remoteMessage.data);
          }
        });

      ...

      const unsubscribe = messaging().onMessage((remoteMessage) => {
        ...
        console.log('current Page FCM :', currentPage);
        ...
      });

      return unsubscribe;
    }
  }, []);

这是日志返回:

 LOG  current page on HomeScreen conversation_event/66260fb009ea6ba6a551c23b 
 LOG  forground current Page :

如果您有任何建议,我将不胜感激,因为我已经解决这个问题好几天了,但没有成功。

react-native firebase-cloud-messaging react-context
1个回答
0
投票

我认为你需要使用 navigationRef.getCurrentRoute() 来停止操作 或您使用过的任何路线

  import {
  StackActions,
  CommonActions,
  createNavigationContainerRef,
} from '@react-navigation/native';

    export const navigationRef = createNavigationContainerRef();

    const currentRouteName = navigationRef.getCurrentRoute()?.name;

    const isFocused = currentRouteName === "pageNameYouWant "
      return isFocused == true ? null : unsubscribe;

我希望我有用并且祝你好运🤞

© www.soinside.com 2019 - 2024. All rights reserved.