簡體   English   中英

React router v6 訪問路由參數並作為道具傳遞

[英]React router v6 access route params and pass as props

在反應路由器 v6 中,如何在無需在組件中使用useParams()的情況下將路由參數傳遞給組件?

這就是我想要做的:

<Route
  path='/'
  element={ProfileComponent username={'thedefault'}
/>
<Route
  exact
  path='/u/:username/'
  render={(props) => 
    <ProfileComponent username={props.match.params.username}/>
  }
/>

我不想將useParams()放在組件中,因為這會將它與 URL 緊密耦合。 例如,如果我想在其他地方渲染另一個 ProfileComponent,它的用戶名與 URL 中的用戶名不同。 它似乎違反了單元測試的最佳實踐,除非我能像我的例子那樣做。

在文檔中,明確指出這是不可能的

通常在 React 中,您會將其作為 prop: 傳遞,但您無法控制該信息,因為它來自 URL。

https://reactrouter.com/docs/en/v6/getting-started/tutorial#reading-url-params

所以,你必須在組件中使用useParams

我不想將useParams()放在組件中,因為這會將它與 URL 緊密耦合。 例如,如果我想在其他地方渲染另一個 ProfileComponent,它的用戶名與 URL 中的用戶名不同。 它似乎違反了單元測試的最佳實踐,除非我能像我的例子那樣做。

任何使用username路由匹配參數的路由仍然可以通過useParams鈎子訪問,但我想我明白你在追求什么。 如果我正確理解您的問題,您是在問如何以通用方式將路由匹配參數 map 路由到組件道具。

為此,您可以簡單地使用包裝器組件來“sip”路由匹配參數並將其傳遞給任何特定道具上的組件。

const ProfileComponentWrapper = () => {
  const { username } = useParams();
  return <ProfileComponent username={username} />;
};

...

<Route
  path='/u/:username/'
  element={<ProfileComponentWrapper />}
/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM