React Native - 如何从推送通知打开路由

React Native - How to open route from push notification

我正在使用 react-navigationreact-native-push-notification。如何在 onNotification 回调中打开某个 StackNavigator's 屏幕?应该在以下时间工作:

我现在只需要它在 Android 中工作。

我尝试将回调函数传递给组件中的通知:

_handleClick() {
  PushNotification.localNotification({
    foreground: false
    userInteraction: false
    message: 'My Notification Message'
    onOpen: () => { this.props.navigation.navigate("OtherScreen") },
  })
}

并在 PushNotification 配置中触发 onOpen

onNotification: function(notification) {
   notification.onOpen()
}

但是函数好像不能传递给notification,除非一个值是一个字符串,它被忽略了,导致onOpen未定义。

好吧,看来我得post自己的解决方案了:)

// src/services/push-notification.js
const PushNotification = require('react-native-push-notification')

export function setupPushNotification(handleNotification) {
  PushNotification.configure({

      onNotification: function(notification) {
        handleNotification(notification)
      },

      popInitialNotification: true,
      requestPermissions: true,
  })

  return PushNotification
}


// Some notification-scheduling component
import {setupPushNotification} from "src/services/push-notification"

class SomeComponent extends PureComponent {

  componentDidMount() {
    this.pushNotification = setupPushNotification(this._handleNotificationOpen)
  }

  _handleNotificationOpen = () => {
    const {navigate} = this.props.navigation
    navigate("SomeOtherScreen")
  }

  _handlePress = () => {
    this.pushNotification.localNotificationSchedule({
      message: 'Some message',
      date: new Date(Date.now() + (10 * 1000)), // to schedule it in 10 secs in my case
    })

  }

  render() {
    // use _handlePress function somewhere to schedule notification
  }

}

这个解决方案是我在 Firebase 的官方网站上找到的,这似乎是最好的 example/sample 解决方案。下面是示例片段以及附加的 link。希望对其他人有帮助。

import React, { useState, useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function App() {
  const navigation = useNavigation();
  const [loading, setLoading] = useState(true);
  const [initialRoute, setInitialRoute] = useState('Home');

  useEffect(() => {
    // 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);
    });

    // 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,
          );
          setInitialRoute(remoteMessage.data.type); // e.g. "Settings"
        }
        setLoading(false);
      });
  }, []);

  if (loading) {
    return null;
  }

  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName={initialRoute}>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Settings" component={SettingsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Link: https://rnfirebase.io/messaging/notifications#handling-interaction

看到我如何使用遗留 react-native-firebase 我想出 id post 我对这个问题的解决方案,因为它与上述使用 RN-firebase V6 的答案之一略有不同.我的解决方案只是略有不同,此解决方案适用于 react-native-firebase v5.x :

的通知处理
import * as React from 'react';
import { Text, TextInput } from 'react-native';
import AppNavigation from './src/navigation';
import { Provider } from 'react-redux';
import { store, persistor } from './src/store/index.js';
import 'react-native-gesture-handler';
import firebase from 'react-native-firebase';
import { PersistGate } from 'redux-persist/integration/react';

export default class App extends React.Component {
    constructor(props) {
        super(props);
        if (firebase.apps.length === 0) {
            firebase.initializeApp({});
        }
    }

    async componentDidMount() {
        // Initialize listener for when a notification has been displayed
        this.removeNotificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification) => {
            // process notification as required... android remote notif's do not have a "channel ID".
        });

        // Initialize listener for when a notification is received
        this.removeNotificationListener = firebase.notifications().onNotification((notification) => {
            // Process notification
        });

        // Listener for notification tap if in FOREGROUND & BACKGROUND
        this.removeNotificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
            // get the action trigger by the notification being opened
            const action = notificationOpen.action;

            // get info about the opened notification
            const info = notificationOpen.notification;

            // log for testing
            console.log('ACTION => ' + action + '\nNOTIFICATION INFO => ' + JSON.stringify(info));
        });

        // Listener for notification tap if app closed
        const notificationOpen = await firebase.notifications().getInitialNotification();
        if (notificationOpen) {
            // App was opened by notification
            const action = notificationOpen.action;
            const info = notificationOpen.notification;

            // log for testing:
            console.log('ACTION => ' + action + '\nNOTIFICATION INFO => ' + JSON.stringify(info));
        }
    }

    componentWillUnmount() {
        // Invoke these functions to un-subscribe the listener
        this.removeNotificationDisplayedListener();
        this.removeNotificationListener();
        this.removeNotificationOpenedListener();
    }

    render() {
        return (
            <Provider store={store}>
                <PersistGate loading={null} persistor={persistor}>
                    <AppNavigation />
                </PersistGate>
            </Provider>
        );
    }
}