React Router 是 React 应用中实现客户端路由的主流方案,以下是核心内容速览:
基础概念 📌
- 路由匹配:通过
<Route>
组件定义路径与组件的映射关系 - 嵌套路由:使用
<Routes>
和<Outlet>
实现多级页面结构 - 动态路由:通过
:param
语法捕获可变路径参数 - 编程导航:使用
useNavigate()
实现程序化跳转
安装与配置 🔧
npm install react-router-dom
路由类型 📜
类型 | 说明 | 示例 |
---|---|---|
精确匹配 | exact 属性限定路径 |
<Route exact path="/home"> |
重定向 | Redirect 组件实现跳转 |
<Route path="/old" element={<Redirect to="/new" />}> |
404 页面 | 未匹配路径的兜底处理 | <Route path="*" element={<NotFound />} /> |
常见用法 📌
- 使用
BrowserRouter
启动路由系统 - 通过
useParams()
获取动态参数 - 用
useLocation()
获取当前路径信息 - 结合
Outlet
实现嵌套路由渲染
路由配置示例 📝
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="users/:id" element={<UserDetail />} />
</Route>
🔗 查看路由配置详解
路由懒加载技巧 🚀
const LazyComponent = React.lazy(() => import('./LazyComponent'));
<Route path="/lazy" element={<LazyComponent />} />
常见问题解答 ❓
- 路由无法匹配?检查路径是否包含多余斜杠
- 404 页面不生效?确认
path="*"
是否在最后定义 - 路由参数获取失败?确保使用
useParams()
而非location.pathname