React router v6 访问路由参数并作为道具传递

React router v6 access route params and pass as props

在 React Router 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 中不同的用户名怎么办?这似乎违反了单元测试的最佳实践,除非我能像我的例子那样做。

在文档中明确指出是不可能的

Normally in React you'd pass this as a prop: , but you don't control that information because it comes from the URL.

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

所以,你必须在组件

中使用useParams

I don't want to put useParams() in the component because this tightly couples it to the URL. For example, what if I wanted to render another ProfileComponent elsewhere, with a different username to that in the URL. It seems to violate best practice for unit testing unless I can do it like my example.

任何使用 username 路由匹配参数的路由仍然可以通过 useParams 挂钩访问,但我想我明白你在追求什么。如果我正确理解你的问题,你是在问如何以通用方式将路由匹配参数映射到组件道具。

为此,您可以简单地使用包装器组件来“吸取”路由匹配参数,并将其传递给任何特定道具上的组件。

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

...

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