如何在 React 导航中从 deep link 的 URI 方案中获取参数?

How to get params from URI scheme of deep link in React navigation?

我正在使用 React Navigation 6 来设置 URI 方案深度链接,这是我的配置方式:

const linking = {
  prefixes: ["wagal://"],
  config: {
    ResetPassword: {
      path: "reset/password/:token",
      params: {
        token: null,
      },
    },
  },
};

function homeStack() {

  return (
    <NavigationContainer linking={linking} fallback={<Text>Loading...</Text>}>
      <Stack.Navigator>
        <Stack.Screen component={ResetPassword} name="ResetPassword" />
        //...
      </Stack.Navigator>
    </NavigationContainer>
  );
}

如果我转到 wagal://reset/password?token=123456789,它会将我重定向到重置密码屏幕中的 App,但我无法从 ResetPassword:

获取令牌参数
function ResetPassword({ route }) {
  const {token} = route.params;
  // ...
}

它抛出以下错误:

undefined is not an object (evaluating route.params.token)

但是如果我尝试使用以下代码在 PasswordReset 屏幕中获取整个 URL,它会显示带有令牌的整个 URI:

  useEffect(() => {
    Linking.getInitialURL().then((url) => {
      console.log(`url`, url);
    });
  }, []);

输出:

wagal://reset/password?token=123456789

我可以使用 slicesubstring 方法,但必须有一种方法可以通过某些方法获取参数?

我也试过这个 navigation.getParam("token"); 但我遇到以下错误:

navigation.getParam is not a function.

有人能帮忙吗?提前致谢。

尝试用这个更改您的配置:

const linking = {
  prefixes: ["wagal://"],
  config: {
    screens:{
      ResetPassword: "reset/password",
    },
  },
};

我遇到了同样的问题,我在您的导航堆栈中找到了可以编辑的解决方案。我使用了本教程:https://reactnavigation.org/docs/screen/

<Stack.Screen name="ResetPassword" component={ResetPassword} getId={({ params }) => params.passwordResetId} options={{ headerShown: false, title: "Réinitialiser le mot de passe" }}/>

然后我在我的关联组件中使用了它

state: {
   id: this.props.match.params.passwordResetId,
}

我也遇到了同样的问题,他做了同样的事情,也得到了同样的结果,当我控制台记录导航道具时,我发现我没有添加那个屏幕,我把堆栈屏幕命名为里面的聊天是底部选项卡,第一个屏幕名称也是聊天,里面是另一个名为 ChatList 的堆栈,这是我获取 ID 的地方,但我没有在我的配置中添加该屏幕。

导航道具日志

{"key": "ChatList-gtKDVQEF0SlR3o_hInYjm", "name": "ChatList", "params": {"id": undefined}}

正确配置后

{"key": "ChatList-gtKDVQEF0SlR3o_hInYjm", "name": "ChatList", "params": {"id": "23"}}

配置错误

config: {
      screens: {
        Intro:"Intro",
        Chats:{
          screens: {
            Chats: {
              path :'test/:id',
              parse:{
                id: (id) => `${id}`
              }
            }
          }
        }
      },
    }

正确配置

config: {
      screens: {
        Intro:"Intro",
        Chats:{
          screens: {
            Chats: {
              screens: {
                ChatList: {
                  path :'test/:id',
                  parse:{
                    id: (id) => `${id}`
                  }
                }
              }
            }
          }
        }
      },
    }

您还可以使用 react-native-deep-linking 并添加一些逻辑并进行导航。这个库有一些有用的功能。