一只斗牛犬
2022-10-21 17:35:20
我使用 react-router-dom 版本 ^5.1.2 并嘗試傳遞動(dòng)態(tài)屬性。我的根組件如下所示: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> );};這是一個(gè)子 RegisterEmailConfirmation 組件:export const RegisterEmailConfirmation: React.FunctionComponent<RouteComponentProps> = ({ match }) => { console.log(match.params.code) // expected 'code' property from the url return ( <SomeContent /> /> );我有一個(gè)來自 BE 的帶有動(dòng)態(tài)“代碼”參數(shù)的 url,它看起來像這樣:注冊/確認(rèn)/電子郵件?code=fjds@dfF。如何呈現(xiàn) RegisterEmailConfirmation 組件并在其中讀取“代碼”屬性?我的代碼有什么問題?
1 回答

湖上湖
TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
當(dāng)您使用功能組件時(shí),您可以u(píng)seParams在組件中使用鉤子。從useParams文檔中查看:
useParams返回 URL 參數(shù)的鍵/值對(duì)的對(duì)象。用它來訪問match.params當(dāng)前的<Route>.
嘗試如下:
export const RegisterEmailConfirmation: React.FunctionComponent<RouteComponentProps> = () => {
let { code } = useParams();
console.log(code);
return <>
{ /* your implementation */ }
</>
}
您也可以導(dǎo)入為:
import { useParams } from "react-router-dom";
我希望這有幫助!
添加回答
舉報(bào)
0/150
提交
取消