React Native - How to open route from push notification

前端 未结 3 953
花落未央
花落未央 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: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 (
        
          
            
            
          
        
      );
    }
    

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

提交回复
热议问题