how to navigate to specific screen after pressing rnfirebase notification

喜你入骨 提交于 2020-06-29 04:27:11

问题


i'm using react native firebase and i'm getting notification whenever is needed, and these notifications have some data to navigate to specific screen. i used the firebase documentation to implement the functionality but it's not working as it's supposed to

Here is the document i've used Firebase & React-Navigation and my code looks something like this :

const Stack = createStackNavigator();
const Router = () => {
    const navigation = useNavigation();
    const [loading, setLoading] = useState(true);
    const [initialRoute, setInitialRoute] = useState('Splash');

useEffect(() => {
    //fcm
    registerAppWithFCM();
    // checkRNFBPermission();

    const unsubscribe = messaging().onMessage(async remoteMessage => {
        console.log('remote DATAAAAAAAAAAAAAAAAAAAAAAAA : ',remoteMessage.data);
        // switch (remoteMessage.data.screen) {
        //     case 'answer':{
        //         console.log('inside switch condition 1 !!!!!!!!!!!!!');
        //         useNavigation().navigate('Profile');
        //         break;
        //     }
        //     case 'AnswerQuestion':{
        //         console.log('inside switch condition 2 !!!!!!!!!!!!!');
        //         useNavigation().navigate('Profile');
        //         break;
        //     }

        //     default:
        //         break;
        // }
        // Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
        // const owner = JSON.parse(remoteMessage.data.owner);
        // const user = JSON.parse(remoteMessage.data.user);
        // const picture = JSON.parse(remoteMessage.data.picture);
    });

    // 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('Profile');

    });
    //  Check whether an initial notification is available
    messaging()
    .getInitialNotification()
    .then(remoteMessage => {
      if (remoteMessage) {
        console.log(
          'Notification caused app to open from quit state:',
          remoteMessage.data, //notification
        );
      }
      setLoading(false);
    });

    messaging().setBackgroundMessageHandler(async remoteMessage => {
        console.log('Message handled in the background!', remoteMessage);
    });

    return unsubscribe;
    //fcm
}, []);

//fcm
checkRNFBPermission = async() => {
    const enabled = await messaging().hasPermission();
    if(enabled){
        messaging()
        .getToken()
        .then(token => {
            // console.log('deviceeeee fcm token ------> ', token);
        });    
    }else{
        requestUserPermission();
    }
}
registerAppWithFCM = async() => {
    await messaging().registerDeviceForRemoteMessages();
}
requestUserPermission = async() =>  {
    const settings = await messaging().requestPermission();
    if (settings) {
        console.log('Permission settings:', settings);
    }
}
//fcm

renderLoading = () => (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'  }}>
        <Text>Domanda</Text>
        <ActivityIndicator size='large' color={colors.darkerTeal} />
    </View>
);

//firebase
if (loading) {
    return null;
}
//firebase
return(
    <Provider store={store}>
        <PersistGate persistor={persistor} loading={this.renderLoading()}>
            <Root>
                <NavigationContainer>
                    <Stack.Navigator initialRouteName={initialRoute} headerMode="none">
                        <Stack.Screen name="Splash" component={Splash} />
                        <Stack.Screen name="Login" component={Login} />
                        <Stack.Screen name="Main" component={Main} />
                        <Stack.Screen name="AppIntro" component={AppIntro} />
                        <Stack.Screen name="Tags" component={Tags} />
                        <Stack.Screen name="Answers" component={Answers} />
                        <Stack.Screen name="Profile" component={Profile} />
                        <Stack.Screen name="EditInfo" component={EditInfo} />
                        <Stack.Screen name="ChangePassword" component={ChangePassword} />
                        <Stack.Screen name="AnswerQuestion" component={AnswerQuestion} />
                        <Stack.Screen name="ContactUs" component={ContactUs} />
                    </Stack.Navigator>
                </NavigationContainer>
            </Root>
        </PersistGate>
    </Provider>
)

};

export default Router;

but when i add usenavigation and i want to use it it throws this error: Error: We couldn't find a navigation object. Is your component inside a screen in a navigator?

i can not use navigation.navigate('Profile'); to navigate to a specific screen.


回答1:


You're receiving the message in App.js whats outside of your StackNavigator. You can use a ref to use the navigation property of the navigator

define the navigator in the top of you app.js

var navigator = null;

then add an ref to the navigator

<Stack.Navigator 
  initialRouteName={initialRoute}
  headerMode="none"
   ref={nav => {
     navigator = nav;
   }}
 >

and push your route inside the receive method

navigator.dispatch(
  NavigationActions.navigate({
     routeName: 'theRoute',
       params: {},
   }),
 );


来源:https://stackoverflow.com/questions/61368217/how-to-navigate-to-specific-screen-after-pressing-rnfirebase-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!