无法从推送通知导航到所选屏幕

Cannot Navigate from Push Notification to Chosen Screen

当用户单击或按下通知时,我想打开一个特定的屏幕。我已经经历了各种 github 问题和堆栈溢出问题和答案,但是似乎没有一个答案或选择的方法来解决这个问题。

最初我使用 PushController class 来处理 onNotification 函数,但我没有将 configure 和 onNotification 函数移动到确实安装在我的组件中创建本地通知的组件。

this.props.navigation.navigate('RouteName'); 

无效。它说 this.props.navigationthis.props.navigation.navigate 未定义。

PushNotification.
            onNotification(notification) {
                console.log('onNotification')
                console.log( notification );
this.props.navigation.navigate('RegisterRoute');
            },

        });

从通知路由或导航到所选屏幕的正确方法是什么。我在 react-native-push-notification 问题和文档中找不到直接的答案。

编辑: 此代码可以在 class 中找到,我在 call/make 本地通知中找到。 触发并调用通知,当单击通知或 onNotification 时,我想导航或路由到另一个屏幕。

组件内部确实挂载了。

PushNotification.configure({

            onNotification(notification) {
                console.log('onNotification')
                console.log( notification );
this.props.navigation.navigate('ChosenScreen');
            },


        });

调用并创建本地通知的函数

function sendNotification(title, pushMessage){
        PushNotification.localNotification({
        message: pushMessage, 
        title: title,
        userInteraction: true,
        alertAction: 'default',// (optional) default: view

       autoCancel: true, 
       largeIcon: "logo", 
       smallIcon: "logo",
       vibrate: true, 
       vibration: 300,

       alertAction: 'default',
       userInfo: 'default'

      });

}

this.props.navigation was undefined 表示您的组件没有 navigation 属性。您必须使用 withNavigation 这是一个高阶组件。

可能您的 onOpened 函数没有正确的作用域,因为它是在 addEventListener 函数中调用的,因此您必须绑定 this.

例如:(好)

 OneSignal.addEventListener('opened', this.onOpened.bind(this));

(错误)- 无导航权限

 OneSignal.addEventListener('received', this.onReceived);

这是我解决问题的方法。

我找到了关于如何创建导航服务的指南(我找不到 link),这有助于解决 props 未定义的问题。我导入了这个服务,我用它来导航。

声明和使用我的通知的地方

import NavigationService from './NavigationService.js';

compnentDidMount(){
  PushNotification.configure({
    onNotification(notification){
    console.log('onNotification')
    console.log(notification );
      NavigationService.navigate('Route', {Params: param});


  },
  });

}

导航服务class

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

export default {
  navigate,
  setTopLevelNavigator,
};