将动态 url 传递给 React Router

我使用 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 组件并在其中读取“代码”属性?我的代码有什么问题?


一只斗牛犬
浏览 92回答 1
1回答

湖上湖

当您使用功能组件时,您可以useParams在组件中使用钩子。从useParams文档中查看:useParams返回 URL 参数的键/值对的对象。用它来访问match.params当前的<Route>.尝试如下:export const RegisterEmailConfirmation: React.FunctionComponent<RouteComponentProps> = () => {&nbsp; let { code } = useParams();&nbsp; console.log(code);&nbsp; return <>&nbsp; &nbsp; &nbsp;{ /* your implementation */ }&nbsp; </>}您也可以导入为:import { useParams } from "react-router-dom";我希望这有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript