首页 > 解决方案 > 在反应原生中按下通知时如何导航到特定屏幕

问题描述

我正在react native push notification使用firebase。我收到通知,一切都很好,但问题是OnOpenNotfication函数启动了两次。它第一次显示 {} 并自动调用自身。当我按下通知时,它也会触发并且什么都不显示,我的意思是通知什么都没有。但是我只想在单击通知时调用 onOpenNotification。我还想将用户从 onOpenNotfication 导航到特定屏幕,但它会自动启动,这就是为什么我不能这是代码。

 componentDidMount = async () => {
   
    fcmService.registerAppWithFCM();
    fcmService.register(onRegister, onNotification, onOpenNotification);
    localNotificationService.configure(onOpenNotification);

    function onRegister(token) {
      console.log('[App] onRegister: ', token);
    }

    function onNotification(notify) {
      console.log('[App] onNotification: ', notify);
      const options = {
        soundName: 'default',
        playSound: true, //,
        // largeIcon: 'ic_launcher', // add icon large for Android (Link: app/src/main/mipmap)
        // smallIcon: 'ic_launcher' // add icon small for Android (Link: app/src/main/mipmap)
      };
      localNotificationService.showNotification(
        0,
        notify.title,
        notify.body,
        notify,
        options,
      );
    }

    function onOpenNotification(notify) {
      console.log('[App] onOpenNotification: ', notify);
      alert('Open Notification: ' + notify.body);
    }
  };

标签: react-nativereact-native-firebasereact-native-push-notification

解决方案


我希望它会帮助你。您可以尝试使用此逻辑。

 import firebase from 'react-native-firebase';
    
    componentDidMount(){
        firebase
            .notifications()
            .onNotificationOpened((notificationOpen: NotificationOpen) => {
              console.log('onNotificationOpened', notificationOpen);
              this.handleNotification(notificationOpen.notification, false);
            });
    }
    
    handleNotification(notification: Notification, appClosed){
       //notification will have your custom data and here you can apply your logics
       //you can use navigation here according to your logic.
       navigatorRef.navigate("routeName");
    }

推荐阅读