React Native - How to open route from push notification

前端 未结 3 941
花落未央
花落未央 2021-02-04 05:43

I\'m using react-navigation and react-native-push-notification. How can I open a certain StackNavigator\'s screen in onNotification<

相关标签:
3条回答
  • 2021-02-04 06:17

    Okay, it seems like I gotta post my own solution :)

    // 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
      }
    
    }
    
    0 讨论(0)
  • 2021-02-04 06:19

    This solution I found over the official website of Firebase and this seems to be the best example/sample work for this. Below is the sample snippet and also the link attached. Hope it help others.

    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

    0 讨论(0)
  • 2021-02-04 06:32

    Seeing as how im using the legacy react-native-firebase I figured id post my solution for this issue, given that its slightly different than one of the above answers which utilizes RN-firebase V6. My solution is only slightly different, this solution works for notification handling with 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>
            );
        }
    }
    
    0 讨论(0)
提交回复
热议问题