为了账号安全,请及时绑定邮箱和手机立即绑定

将动态 url 传递给 React Router

将动态 url 传递给 React Router

一只斗牛犬 2022-10-21 17:35:20
我使用 react-router-dom 版本 ^5.1.2 并尝试传递动态属性。我的根组件如下所示:export const RegisterRoutes: React.FunctionComponent<RouteComponentProps> = ({  match,}: RouteComponentProps) => {  const root = match.url;  return (    <Switch>      <Route exact path={`${root}/success`} component={RegisterSuccess} />      <Route exact path={`${root}/success/email`} component={RegisterEmail} />      <Route exact path={`${root}/confirmation/email/:code`} component={RegisterEmailConfirmation} />      <Redirect to={root} />    </Switch>  );};这是一个子 RegisterEmailConfirmation 组件:export const RegisterEmailConfirmation: React.FunctionComponent<RouteComponentProps> = ({ match }) => {  console.log(match.params.code) // expected 'code' property from the url   return (     <SomeContent />    />  );我有一个来自 BE 的带有动态“代码”参数的 url,它看起来像这样:注册/确认/电子邮件?code=fjds@dfF。如何呈现 RegisterEmailConfirmation 组件并在其中读取“代码”属性?我的代码有什么问题?
查看完整描述

1 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

当您使用功能组件时,您可以useParams在组件中使用钩子。从useParams文档中查看:


useParams返回 URL 参数的键/值对的对象。用它来访问match.params当前的<Route>.


尝试如下:


export const RegisterEmailConfirmation: React.FunctionComponent<RouteComponentProps> = () => {

  let { code } = useParams();


  console.log(code);


  return <>

     { /* your implementation */ }

  </>

}

您也可以导入为:


import { useParams } from "react-router-dom";

我希望这有帮助!


查看完整回答
反对 回复 2022-10-21
  • 1 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信