首页 > 解决方案 > 如何从 React 导航中的深层链接的 URI 方案中获取参数?

问题描述

我正在使用 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它会将我重定向到重置密码屏幕中的应用程序,但我无法从以下位置获取令牌参数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

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

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

navigation.getParam is not a function.

任何人都可以帮忙吗?提前致谢。

标签: reactjsreact-nativereact-navigationdeep-linkingurl-scheme

解决方案


I have had the same problem and I found out this solution to edit in your Navigation stack. I used this tutorial : 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" }}/>

Then I used it in my associated component with this

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

推荐阅读