[英]React router v6 access route params and pass as props
In react router v6, how can I pass route params to a component without the need to use useParams()
in the component?在反应路由器 v6 中,如何在无需在组件中使用
useParams()
的情况下将路由参数传递给组件?
This is what I want to do:这就是我想要做的:
<Route
path='/'
element={ProfileComponent username={'thedefault'}
/>
<Route
exact
path='/u/:username/'
render={(props) =>
<ProfileComponent username={props.match.params.username}/>
}
/>
I don't want to put useParams()
in the component because this tightly couples it to the URL.我不想将
useParams()
放在组件中,因为这会将它与 URL 紧密耦合。 For example, what if I wanted to render another ProfileComponent elsewhere, with a different username to that in the URL.例如,如果我想在其他地方渲染另一个 ProfileComponent,它的用户名与 URL 中的用户名不同。 It seems to violate best practice for unit testing unless I can do it like my example.
它似乎违反了单元测试的最佳实践,除非我能像我的例子那样做。
In the docs, it is clearly specified that it is not possible在文档中,明确指出这是不可能的
Normally in React you'd pass this as a prop: , but you don't control that information because it comes from the URL.
通常在 React 中,您会将其作为 prop: 传递,但您无法控制该信息,因为它来自 URL。
https://reactrouter.com/docs/en/v6/getting-started/tutorial#reading-url-params https://reactrouter.com/docs/en/v6/getting-started/tutorial#reading-url-params
So, you have to use useParams
in the component所以,你必须在组件中使用
useParams
I don't want to put
useParams()
in the component because this tightly couples it to the URL.我不想将
useParams()
放在组件中,因为这会将它与 URL 紧密耦合。 For example, what if I wanted to render another ProfileComponent elsewhere, with a different username to that in the URL.例如,如果我想在其他地方渲染另一个 ProfileComponent,它的用户名与 URL 中的用户名不同。 It seems to violate best practice for unit testing unless I can do it like my example.
它似乎违反了单元测试的最佳实践,除非我能像我的例子那样做。
Any route using a username
route match param would still be accessible via the useParams
hook, but I think I understand what you are after.任何使用
username
路由匹配参数的路由仍然可以通过useParams
钩子访问,但我想我明白你在追求什么。 If I understand your question correctly you are asking how to map a route match param to a component prop in a generic way.如果我正确理解您的问题,您是在问如何以通用方式将路由匹配参数 map 路由到组件道具。
For this you can simply use a wrapper component to "sip" the route match param and pass it along to your component on any specific prop.为此,您可以简单地使用包装器组件来“sip”路由匹配参数并将其传递给任何特定道具上的组件。
const ProfileComponentWrapper = () => {
const { username } = useParams();
return <ProfileComponent username={username} />;
};
... ...
<Route
path='/u/:username/'
element={<ProfileComponentWrapper />}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.