本文详细介绍了如何在React router v6中实现带有认证保护的嵌套路由。通过使用Outlet组件,我们可以在父级布局中动态渲染子路由内容,从而确保用户在导航时保持界面布局的连贯性。文章涵盖了主应用路由配置、私有路由守卫、布局组件设计以及内容组件的实现,为构建复杂的用户界面提供了清晰的指导。
在现代单页应用(spa)中,构建具有复杂导航和权限控制的仪表盘(dashboard)是常见需求。例如,一个仪表盘可能包含一个固定的侧边栏或顶部导航,而主要内容区域则根据用户的选择动态加载不同的组件(如用户列表、产品管理等)。同时,这些内容通常需要用户登录后才能访问。react router v6 提供了一套强大且直观的api来解决这些问题,特别是通过其“嵌套路由”和“私有路由”概念。
核心概念解析
在深入代码实现之前,我们首先理解两个关键概念:
- 私有路由 (private Routes): 指的是那些只有经过认证(登录)的用户才能访问的路由。未认证的用户尝试访问时,会被重定向到登录页面或其他指定页面。这通常通过一个高阶组件(HOC)或一个包装器组件来实现。
- 嵌套路由 (Nested Routes): 允许你在一个父级路由下定义子路由。当父级路由被激活时,其对应的组件会渲染,并且该组件内部可以指定一个区域(通过 Outlet 组件)来渲染当前激活的子路由组件。这对于构建具有持久布局(如侧边栏、头部)的应用程序非常有用。
实现步骤与代码示例
我们将通过构建一个简单的仪表盘应用来演示如何结合使用私有路由和嵌套路由。
1. 定义主应用路由 (App.jsx)
App.jsx 是我们应用路由的入口。在这里,我们配置了登录页、一个私有路由守卫,以及仪表盘的嵌套路由结构。
// App.jsx import React from 'react'; import { Routes, Route, Navigate } from 'react-router-dom'; import SignIn from './auth/SignIn'; // 登录组件 import Layout from './components/Layout'; // 仪表盘布局组件 import Users from './components/Users'; // 用户列表组件 import Products from './components/Products'; // 产品列表组件 import ProtectedRoute from './auth/ProtectedRoute'; // 私有路由守卫 function App() { return ( <div className="App"> <Routes> {/* 公开路由:登录页面 */} <Route path="/" element={<SignIn />} /> {/* 保护的路由组:所有需要登录才能访问的路由都放在这里 */} <Route element={<ProtectedRoute />}> {/* 仪表盘父级布局路由 */} {/* 当访问 /dashboard 时,Layout 组件会被渲染 */} <Route path="/dashboard" element={<Layout />}> {/* 嵌套子路由:当访问 /dashboard/users 时,Users 组件会在 Layout 的 Outlet 中渲染 */} <Route path="users" element={<Users />} /> {/* 嵌套子路由:当访问 /dashboard/products 时,Products 组件会在 Layout 的 Outlet 中渲染 */} <Route path="products" element={<Products />} /> {/* 默认子路由:当只访问 /dashboard 时,默认重定向到 /dashboard/users */} <Route index element={<Navigate to="users" replace />} /> </Route> </Route> {/* 匹配所有未定义路由,重定向到登录页 */} <Route path="*" element={<Navigate to="/" replace />} /> </Routes> </div> ); } export default App;
关键点说明:
- Route element={
}:这是一个“布局路由”,它本身不渲染任何ui,但它的 element(ProtectedRoute)会决定是否允许其子路由被渲染。 - Route path=”/dashboard” element={
}:这是我们的仪表盘布局路由。所有其下的子路由都将会在 Layout 组件内部的 位置渲染。 - path=”users” 和 path=”products”:这些是相对路径。当它们嵌套在 /dashboard 之下时,完整的路径将是 /dashboard/users 和 /dashboard/products。
- index element={
}:index 路由用于指定当父路由路径(/dashboard)被精确匹配时,应该渲染哪个子路由。这里我们将其重定向到 users 页面,作为仪表盘的默认入口。
2. 创建私有路由守卫 (ProtectedRoute.jsx)
ProtectedRoute 组件负责检查用户是否已登录。如果未登录,它会将用户重定向到登录页面;如果已登录,它将渲染其子路由内容。
// auth/ProtectedRoute.jsx import React from 'react'; import { Outlet, Navigate } from 'react-router-dom'; const ProtectedRoute = () => { // 在实际应用中,这里需要实现真正的认证逻辑 // 例如,从 localStorage 获取 token,或检查 redux/Context 中的用户状态 const isAuthenticated = true; // 示例:假设用户已认证 return isAuthenticated ? <Outlet /> : <Navigate to="/" replace />; }; export default ProtectedRoute;
注意事项:
- isAuthenticated 变量应替换为实际的认证检查逻辑。
- Outlet 组件是 React Router v6 的核心,它会渲染当前匹配到的子路由组件。
3. 设计布局组件 (Layout.jsx)
Layout 组件是仪表盘的整体框架,包含固定的导航菜单和动态内容区域。
// components/Layout.jsx import React from 'react'; import { Col, Row } from 'antd'; // 假设使用 Ant Design 进行布局 import { Link, Outlet } from 'react-router-dom'; // 导入 Outlet const Layout = () => { return ( <Row style={{ minHeight: '100vh' }}> {/* 左侧菜单栏 */} <Col xxl={4} xl={5} lg={6} md={6} sm={6} xs={6} style={{ borderRight: '1px solid #f0f0f0' }}> <div className="left-menu" style={{ padding: '20px' }}> <h2>Dashboard</h2> <ul> <li style={{ marginBottom: '10px' }}> {/* 链接到嵌套子路由 */} <Link to="/dashboard/users" style={{ textDecoration: 'none', color: '#1890ff' }}>Users</Link> </li> <li> {/* 链接到嵌套子路由 */} <Link to="/dashboard/products" style={{ textDecoration: 'none', color: '#1890ff' }}>Products</Link> </li> </ul> </div> </Col> {/* 右侧内容区域 */} <Col xxl={20} xl={19} lg={18} md={18} sm={18} xs={18} style={{ padding: '20px' }}> <div className="content-area"> <Outlet /> {/* !!!关键:这里会渲染当前激活的子路由组件(Users 或 Products) */} </div> </Col> </Row> ); }; export default Layout;
关键点说明:
-
:这是实现嵌套路由的核心。当 Layout 组件被渲染时,如果存在匹配的子路由(如 /dashboard/users),那么 Users 组件就会在这个 的位置渲染。这样,左侧菜单保持不变,只有右侧内容区域发生变化。 - Link to=”/dashboard/users”:导航链接需要指向完整的嵌套路径。
4. 登录页面 (SignIn.jsx)
SignIn 组件负责处理用户登录逻辑,登录成功后导航到仪表盘。
// auth/SignIn.jsx import React from "react"; import { useNavigate } from "react-router-dom"; const SignIn = () => { const navigate = useNavigate(); const loginAuth = () => { // 实际的登录认证逻辑,例如调用API验证用户名密码 // 假设认证成功 console.log("Attempting login..."); // 登录成功后,导航到仪表盘的默认页面 navigate("/dashboard"); }; return ( <div style={{ padding: '50px', textAlign: 'center' }}> <h2>Sign In</h2> <input type="text" placeholder="email" style={{ margin: '10px', padding: '8px' }} /> <br /> <input type="password" placeholder="password" style={{ margin: '10px', padding: '8px' }} /> <br /> <button onClick={loginAuth} style={{ padding: '10px 20px', cursor: 'pointer' }}>Login</button> </div> ); }; export default SignIn;
5. 内容组件 (Users.jsx, Products.jsx)
这些是简单的组件,用于演示在布局中渲染的不同内容。
// components/Users.jsx import React from 'react'; const Users = () => { return ( <div> <h3>Users List</h3> <p>This is the content for the Users section.</p> {/* 实际的用户列表数据和UI */} </div> ); }; export default Users; // components/Products.jsx import React from 'react'; const Products = () => { return ( <div> <h3>Products Catalog</h3> <p>This is the content for the Products section.</p> {/* 实际的产品目录数据和UI */} </div> ); }; export default Products;
注意事项
- 路径的相对性: 在嵌套路由中,子路由的 path 如果不以 / 开头,则会被视为相对于父路由的路径。例如,在 /dashboard 路由下,path=”users” 对应的完整路径是 /dashboard/users。
- 认证逻辑: ProtectedRoute 中的 isAuthenticated 变量是一个占位符。在实际应用中,你需要从全局状态管理(如 Context API, Redux)、本地存储(localStorage)或通过 API 调用来获取用户的认证状态。
- 导航方式: 使用 Link 组件进行声明式导航,或者使用 useNavigate 钩子进行编程式导航。
- css/样式: 示例代码中包含了一些简单的内联样式,实际项目中应使用独立的CSS文件、CSS Modules 或 styled-components 等方式来管理样式。
总结
通过上述步骤,我们成功地在 React Router v6 中实现了带有私有路由的嵌套视图。核心在于利用 ProtectedRoute 进行权限控制,并通过在父级布局组件(如 Layout)中使用