亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將動態 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 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號