首页 > 解决方案 > 将参数处理为获取的对象

问题描述

我正在使用带有 Firebase 集成的 React Native v0.63+ 和 React Navigation 5。我必须解决两个问题,这些问题涉及到应用程序的某些部分的深度链接,为了呈现视图,需要一些props.route.params包含的对象,例如profile,这些对象可能包含也可能不包含敏感数据以放入纯文本 url。

为了导航到某个配置文件而不将整个配置文件字符串化为一个无休止的 url,我认为我可以将其解析idprofile必须从 api 获取以便由视图呈现的内容。但是我误解了react-navigation parse功能。

但是,我很难找出正确的方法。我该怎么做呢?

这是我的linking对象:

export const linking = {
    prefixes: ['myapp://'],
    config: {
        Login: 'login',
        Signup: 'signup',
        PersonalInfo: 'personalinfo',
        Drawer: {
            path: "app",
            screens: {
                Saved: "saved",
                Details: "details",
                Trend: "trend",
                Profile: {
                    path: "profile/:id?",
                    parse: {
                        id: Number, // <-- this is my profile id param
                    },
                },
                EditProfile: "editprofile",
                Multimedia: "multimedia",
                Premium: "premium",
                Chat: "chat",
                LikeView: "likes",
                ReseedView: "reseeds",
                Tabs: {
                    path: "tabs",
                    exact: true,
                    screens: {
                        Main: "main",
                        Escribir: "escribir",
                        Notificaciones: "notificaciones",
                        Mensajes: "mensajes"
                    }
                },
            },
        },
    },

这就是应用程序已经处理传入profile以呈现它的方式:

//from any component within navigation reach
navigation.push('Profile',{profile, isMine});
//Profile component
const ProfileScreen = (props) => {
  const { profile, isMine } = props.route.params;
  const [profileOwner, setProfile] = useState(profile);
//...

标签: react-nativeasync-awaitdeep-linkingreact-navigation-v5

解决方案


使用解构 props 对象来始终使用参数的更好方法。这是 JavaScript 对象的默认 ES6 语法。

For Ex :

    const { isMine } = props.route.params;

因此,我建议您遵循这种方法来解构和使用您的对象,甚至在您的组件内部进行初始化或操作,而不是直接访问像“props.route.params.profile”这样的整个参数对象


推荐阅读