You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React-Router-Dom时如何省略父路径前缀定义子路由?

React Router嵌套路由省略父路径前缀实现方案

你可以根据你使用的React Router版本选择对应实现方式:

针对React Router v5版本

你只需要通过useRouteMatch Hook获取父路由的匹配路径,拼接作为子路由的前缀即可:

  1. 首先保持App.js中的现有代码不变(注意父路由/profile不要加exact属性,否则无法匹配子路由)
  2. 修改Profile.js代码如下:
// Profile.js
import { useRouteMatch, Switch, Route } from 'react-router-dom';

function Profile() {
  // 获取父路由匹配对象,match.path就是定义的父路由路径"/profile"
  const match = useRouteMatch();

  return (
    <div>
      {/* 其他Profile公共内容 */}
      <Switch>
        <Route exact path={`${match.path}/posts`}>
          <Posts />
        </Route>
        <Route path={`${match.path}/comments`}>
          <Comments />
        </Route>
      </Switch>
    </div>
  )
}

如果是类组件,可以用withRouter高阶组件包裹Profile组件,从props中获取match对象即可。

注意:match.path是路由定义的路径模板(比如父路由是/profile/:id时,match.path就是/profile/:id),match.url是实际匹配到的路径值(比如/profile/123),可根据实际业务场景选择使用。

针对React Router v6版本

v6对嵌套路由做了原生简化,不需要手动拼接路径,操作更简单:

  1. 先修改App.js中的父路由配置,末尾加/*声明允许匹配子路径:
// App.js
import { Routes, Route } from 'react-router-dom';

// ...
<Routes>
  <Route path="/" element={<Home />} />
  {/* 末尾加/* 声明支持嵌套子路由 */}
  <Route path="/profile/*" element={<Profile />} />
</Routes>
  1. Profile.js中的子路由直接写相对路径即可,完全省略父前缀:
// Profile.js
import { Routes, Route } from 'react-router-dom';

function Profile() {
  return (
    <div>
      {/* 其他Profile公共内容 */}
      <Routes>
        {/* 直接写子路径即可,默认继承父路径/profile作为前缀 */}
        <Route path="posts" element={<Posts />} />
        <Route path="comments" element={<Comments />} />
      </Routes>
    </div>
  )
}

内容的提问来源于stack exchange,提问作者noiseymur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:06:03