如何使用 React-Navigation 深层链接将参数作为对象传递?

Kar*_*mK3 2 parameters deep-linking reactjs react-native react-navigation

我使用 React-Navigation 深度链接从 Url 获取参数,但我想将这些参数传递给一个对象。现在我这样做:

prefixes: [Linking.makeUrl('/'), 'https://test.app', 'https://*.test.app'],
  config: {
    screens: {
      App: {
        screens: {
          Chat: {
            path: 'chat/:firstName/:lastName/:birthdate',
            parse: {
              firstName: (firstName: string) => decodeURIComponent(firstName),
              lastName: (lastName: string) => decodeURIComponent(lastName),
              birthdate: (birthdate: string) => decodeURIComponent(birthdate),
            },
          },
Run Code Online (Sandbox Code Playgroud)

这是结果:

 const { firstName, lastName, birthdate} = route.params
Run Code Online (Sandbox Code Playgroud)

我需要的是一个带有名字、姓氏、出生日期的对象:

const { userObject } = route.params
Run Code Online (Sandbox Code Playgroud)

Tom*_*m S 6

您可以使用getStateFromPath根据需要配置参数。

像这样的东西应该有效。注意:我还没有使用嵌套屏幕进行测试。您可能需要稍微修改一下以处理嵌套屏幕。

import { getStateFromPath } from '@react-navigation/native';

const linking = {
  prefixes: [Linking.makeUrl('/'), 'https://test.app', 'https://*.test.app'],
  config: {
    screens: {
      App: {
        screens: {
          Chat: {
            path: 'chat/:firstName/:lastName/:birthdate',
            parse: {
              firstName: (firstName: string) => decodeURIComponent(firstName),
              lastName: (lastName: string) => decodeURIComponent(lastName),
              birthdate: (birthdate: string) => decodeURIComponent(birthdate),
            },
          },
        },
      },
    },
  },
  getStateFromPath: (path, options) => {
    const state = getStateFromPath(path, options);
    const newState = {
      ...state,
      routes: state.routes.map(route => {
        if (route.name === 'Chat') {
          // modify your params however you like here!
          return {
            ...route,
            params: { userObject: route.params }
          }
        } else {
          return route
        }
      }),
    };
    return newState;
  },
}

Run Code Online (Sandbox Code Playgroud)