如何通过 React-Router-Dom 省略父路径来定义子路径?
How can sub paths be defined by omitting the parent path with React-Router-Dom?
所以,假设我有一个根据路径呈现不同组件的配置文件页面。
例如:
/profile/posts
在配置文件中呈现帖子组件。
/profile/comments
在配置文件中呈现评论组件。
我一般是先渲染"/profile"
路径的Profile页面,然后在其中根据上面提到的Routes渲染相关的Component。我想做的是,省略 Profile 中 Route 组件中定义的路径的 "/profile"
部分,只保留其余部分。如何在不破坏路由的情况下做到这一点?
查看下面代码中的注释:
// App.js
// ...
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/profile"> // Profile page is rendered here
<Profile />
</Route>
</Switch>
// ...
// Profile.js
// ...
<Switch>
<Route exact path="/profile/posts"> // I want to omit "/profile" part of the path.
<Posts />
</Route>
<Route path="/profile/comments"> // I want to omit "/profile" part of the path.
<Comments />
</Route>
</Switch>
// ...
在嵌套路由时,如果您不想“复制”路径详细信息,那么您可以从 match 对象中获取它们,特别是用于构建嵌套路由的 path
值。
假设Profile
是一个函数组件,使用useRouteMatch钩子访问当前匹配路由的path
值。如果它是一个 class 组件,那么它将必须访问路由属性以获取 this.props.match
.
// Profile.js
const { path } = useRouteMatch();
// ...
<Switch>
<Route path={`${path}/posts`}>
<Posts />
</Route>
<Route path={`${path}/comments`}>
<Comments />
</Route>
</Switch>
// ...
这里有更深入的 nested routing demo 来自 `react-router-dom.
所以,假设我有一个根据路径呈现不同组件的配置文件页面。 例如:
/profile/posts
在配置文件中呈现帖子组件。
/profile/comments
在配置文件中呈现评论组件。
我一般是先渲染"/profile"
路径的Profile页面,然后在其中根据上面提到的Routes渲染相关的Component。我想做的是,省略 Profile 中 Route 组件中定义的路径的 "/profile"
部分,只保留其余部分。如何在不破坏路由的情况下做到这一点?
查看下面代码中的注释:
// App.js
// ...
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/profile"> // Profile page is rendered here
<Profile />
</Route>
</Switch>
// ...
// Profile.js
// ...
<Switch>
<Route exact path="/profile/posts"> // I want to omit "/profile" part of the path.
<Posts />
</Route>
<Route path="/profile/comments"> // I want to omit "/profile" part of the path.
<Comments />
</Route>
</Switch>
// ...
在嵌套路由时,如果您不想“复制”路径详细信息,那么您可以从 match 对象中获取它们,特别是用于构建嵌套路由的 path
值。
假设Profile
是一个函数组件,使用useRouteMatch钩子访问当前匹配路由的path
值。如果它是一个 class 组件,那么它将必须访问路由属性以获取 this.props.match
.
// Profile.js
const { path } = useRouteMatch();
// ...
<Switch>
<Route path={`${path}/posts`}>
<Posts />
</Route>
<Route path={`${path}/comments`}>
<Comments />
</Route>
</Switch>
// ...
这里有更深入的 nested routing demo 来自 `react-router-dom.