单击通知时,将本机导航到特定屏幕

问题描述

我正在尝试在用户点击他们收到的通知时实现导航。我使用 expo-notifications 成功接收通知并接受来自 API 的数据(路由),但在用户点击通知时无法导航到另一个屏幕。

使用通知

export default useNotifications = () => {
    ...

    useEffect(() => {
        registerForPushNotificationsAsync().then((token) => {
            setExpoPushToken(token);
            alert(token);
        });

        notificationListener.current = Notifications.addNotificationReceivedListener(
            (notification) => {
                setNotification(notification);
                console.log(notification);
            }
        );

        responseListener.current = Notifications.addNotificationResponseReceivedListener(
            (response) => {
                //notification is received OK
                console.log("opened");
                
                //here I want to navigate to another screen using rootnavigation
                navigation.navigate("Account"); 

                //alert shows fine
                alert("ok");
            }
        );

        return () => {
            Notifications.removeNotificationSubscription(notificationListener);
            Notifications.removeNotificationSubscription(responseListener);
        };
    },[]);
};

导航器:

const SettingsNavigation = ({ component }) => {
    useNotifications();

    return (
        <Stack.Navigator mode="card" screenoptions={{ headerShown: false }}>
            <Stack.Screen
                name="Main"
                component={component}
                options={{ title: "Home" }}
            />

            <Stack.Screen
                name="TiMetable"
                component={TiMetableScreenBoss}
                options={menuOptions("Schedule")}
            />

            <Stack.Screen
                name="Account"
                component={AccountNavigator}
                options={menuOptions("Account",false)}
            />
        </Stack.Navigator>
    );
};

根导航:

import React from "react";

export const navigationRef = React.createRef();

const navigate = (name,params) =>
    navigationRef.current?.navigate(name,params);

export default {
    navigate,};

app.js:

import { navigationRef } from "./app/navigation/rootNavigation"; //rootnavigation

<NavigationContainer navigationRef={navigationRef}>
    <CustomNavigator>   
</NavigationContainer>

解决方法

假设您使用的是 react-navigationNavigationContainer 接受普通的 ref 属性:

<NavigationContainer ref={navigationRef}>
    <CustomNavigator>   
</NavigationContainer>

NavigationContainer docs

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...