React Router Dom v6 全面教程 从基础到高级实战详解 如何正确使用路由配置和嵌套路由以及路由守卫和动态路由等核心功能解决单页应用导航问题

引言:React Router Dom v6 概述
React Router Dom v6 是 React 生态中最流行的路由库,它为单页应用(SPA)提供了强大的导航解决方案。与之前的版本相比,v6 版本引入了大量重大改进,包括更声明式的 API、更好的 TypeScript 支持、更灵活的路由配置以及更强大的嵌套路由功能。
为什么选择 React Router Dom v6?
声明式路由
:使用 JSX 语法定义路由,更符合 React 的设计理念
嵌套路由支持
:原生支持复杂的路由层级结构
路由守卫
:提供了灵活的路由保护机制
动态路由
:支持基于数据的动态路由配置
更好的性能
:优化了路由匹配算法
TypeScript 原生支持
:完整的 TypeScript 类型定义
适用场景
单页应用(SPA)导航
复杂的用户权限系统
动态菜单和路由
需要路由守卫的应用
多级嵌套页面结构
基础安装与配置
安装步骤
# 使用 npm 安装
npm install react-router-dom

# 使用 yarn 安装
yarn add react-router-dom

# 使用 pnpm 安装
pnpm add react-router-dom
基础配置示例
// src/App.jsx
import React from ‘react’;
import { BrowserRouter, Routes, Route } from ‘react-router-dom’;
import Home from ‘./pages/Home’;
import About from ‘./pages/About’;
import Contact from ‘./pages/Contact’;

function App() {
return (


} />
} />
} />


);
}

export default App;
不同类型的 Router
React Router Dom v6 提供了多种 Router 类型,适用于不同场景:
import {
BrowserRouter,
HashRouter,
MemoryRouter,
unstable_HistoryRouter
} from ‘react-router-dom’;

// 1. BrowserRouter – 使用 HTML5 History API(推荐)

{/* 你的路由配置 */}

// 2. HashRouter – 使用 URL hash(兼容性更好)

{/* 你的路由配置 */}

// 3. MemoryRouter – 内存中的路由(测试用)

{/* 你的路由配置 */}

// 4. HistoryRouter – 自定义 history 对象
import { createBrowserHistory } from ‘history’;
const history = createBrowserHistory();


{/* 你的路由配置 */}

路由配置详解
基础路由配置
import { Routes, Route } from ‘react-router-dom’;

// 基础路由配置

{/* 精确匹配路径 */}
} exact />

{/* 静态路由 */}
} />

{/* 动态参数路由 */}
} />

{/* 可选参数路由 */}
} />

{/* 通配符路由 */}
} />

路由参数详解
// 使用 useParams 获取路由参数
import { useParams, useSearchParams } from ‘react-router-dom’;

// 1. 路径参数 (Path Parameters)
function UserProfile() {
const { id } = useParams();
return

User ID: {id}

;
}

// 路由配置
} />

// 2. 查询参数 (Query Parameters)
function SearchPage() {
const [searchParams] = useSearchParams();
const query = searchParams.get(‘q’);
const page = searchParams.get(‘page’) || 1;

return (

搜索关键词: {query}

当前页: {page}

);
}

// 访问 /search?q=react&page=2
路由索引和布局
// 使用 index 路由作为默认子路由

}>
{/* 当访问 /dashboard 时显示 */}
} />

{/* 当访问 /dashboard/profile 时显示 */}
} />

{/* 当访问 /dashboard/settings 时显示 */}
} />

// DashboardLayout 组件
function DashboardLayout() {
return (

Dashboard Header


{/* 子路由内容将在这里渲染 */}

);
}
嵌套路由详解
嵌套路由基础
嵌套路由是 React Router v6 的核心特性,它允许你在组件内部定义子路由:
// App.jsx
import { Routes, Route } from ‘react-router-dom’;
import Layout from ‘./components/Layout’;
import Dashboard from ‘./pages/Dashboard’;
import Profile from ‘./pages/Profile’;
import Settings from ‘./pages/Settings’;

function App() {
return (

{/* 布局路由 */}
}>
{/* 嵌套路由 */}
}>
} />
} />
} />

{/* 独立的嵌套路由 */}
}>
} />
} />
} />



);
}
嵌套路由的 Outlet 渲染机制
// Layout.jsx – 父组件
import { Outlet, Link, useLocation } from ‘react-router-dom’;

function Layout() {
const location = useLocation();

return (

我的应用


{/* 子路由内容将在这里渲染 */}

当前路径: {location.pathname}

);
}

// Dashboard.jsx – 子组件
import { Outlet, Link, useParams } from ‘react-router-dom’;

function Dashboard() {
const { id } = useParams(); // 如果有父路由参数

return (

仪表板

{/* 进一步的子路由 */}

);
}
相对路由与绝对路由
// 相对路由(推荐)
function Parent() {
return (

} />

);
}

// 在子组件中使用相对链接
function Child() {
// 这会链接到 /parent/child/grandchild
return Grandchild;
}

// 绝对路由
function Child() {
// 使用 / 开头的路径是绝对路径
return Grandchild;
}

// 使用 .. 返回上一级
function DeepComponent() {
// 链接到 /parent/child
return Back to Child;
}
路由守卫与权限控制
基础路由守卫实现
路由守卫是保护路由访问权限的重要机制:
// PrivateRoute.jsx – 基础私有路由组件
import { Navigate, useLocation } from ‘react-router-dom’;
import { useAuth } from ‘./AuthContext’;

function PrivateRoute({ children }) {
const { user } = useAuth();
const location = useLocation();

if (!user) {
// 重定向到登录页,并保存当前路径
return ;
}

return children;
}

// 使用方式




}
/>

高级权限控制组件
// AuthRoute.jsx – 高级权限路由组件
import { Navigate, useLocation } from ‘react-router-dom’;
import { useAuth } from ‘./AuthContext’;

// 权限级别定义
const PERMISSIONS = {
ADMIN: [‘admin’, ‘user’, ‘guest’],
USER: [‘user’, ‘guest’],
GUEST: [‘guest’],
};

function AuthRoute({ children, requiredRole = null, requiredPermission = null }) {
const { user, loading } = useAuth();
const location = useLocation();

// 加载中状态
if (loading) {
return

Loading…

;
}

// 未登录处理
if (!user) {
return ;
}

// 检查角色权限
if (requiredRole && user.role !== requiredRole) {
return ;
}

// 检查具体权限
if (requiredPermission && !user.permissions.includes(requiredPermission)) {
return ;
}

return children;
}

// 使用示例

{/* 需要登录 */}



}
/>

{/* 需要管理员角色 */}



}
/>

{/* 需要特定权限 */}



}
/>

路由守卫的 Hook 实现
// useAuth.js – 自定义 Hook
import { useContext, createContext, useState, useEffect } from ‘react’;
import { useNavigate, useLocation } from ‘react-router-dom’;

const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
const location = useLocation();

// 模拟登录
const login = async (username, password) => {
setLoading(true);
try {
// 模拟 API 调用
const response = await fakeAuthAPI(username, password);
setUser({
id: response.id,
username,
role: response.role,
permissions: response.permissions,
});

// 重定向到原目标页面或默认页面
const from = location.state?.from?.pathname || ‘/dashboard’;
navigate(from, { replace: true });
} finally {
setLoading(false);
}
};

// 登出
const logout = () => {
setUser(null);
navigate(‘/login’, { replace: true });
};

// 检查权限的辅助函数
const hasPermission = (permission) => {
return user?.permissions?.includes(permission) || false;
};

const hasRole = (role) => {
return user?.role === role || false;
};

const value = {
user,
loading,
login,
logout,
hasPermission,
hasRole,
};

return {children};
};

export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error(‘useAuth must be used within AuthProvider’);
}
return context;
};

// 模拟认证 API
const fakeAuthAPI = (username, password) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (username === ‘admin’ && password === ‘admin123’) {
resolve({
id: 1,
role: ‘ADMIN’,
permissions: [‘admin’, ‘user’, ‘guest’, ‘manage_settings’],
});
} else if (username === ‘user’ && password === ‘user123’) {
resolve({
id: 2,
role: ‘USER’,
permissions: [‘user’, ‘guest’],
});
} else {
reject(new Error(‘Invalid credentials’));
}
}, 1000);
});
};
完整的路由守卫应用示例
// App.jsx – 完整的路由守卫配置
import { BrowserRouter, Routes, Route, Navigate } from ‘react-router-dom’;
import { AuthProvider, useAuth } from ‘./AuthContext’;
import PrivateRoute from ‘./components/PrivateRoute’;
import AuthRoute from ‘./components/AuthRoute’;

// 页面组件
const Home = () =>

首页

;
const Login = () => {
const { login } = useAuth();
return (

登录


);
};
const Dashboard = () =>

仪表板

;
const AdminPanel = () =>

管理面板

;
const Settings = () =>

设置

;
const Profile = () =>

个人资料

;
const Unauthorized = () =>

无权限访问

;
const NotFound = () =>

页面不存在

;

function AppRoutes() {
return (

{/* 公共路由 */}
} />
} />
} />

{/* 需要登录的路由 */}



}
/>




}
/>

{/* 需要管理员权限的路由 */}



}
/>

{/* 需要特定权限的路由 */}



}
/>

{/* 404 路由 */}
} />

);
}

function App() {
return (





);
}

export default App;
动态路由与数据加载
动态路由配置
动态路由允许你根据数据动态生成路由配置:
// 动态路由配置示例
import { useEffect, useState } from ‘react’;
import { Routes, Route } from ‘react-router-dom’;

function DynamicRoutes() {
const [routes, setRoutes] = useState([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
// 模拟从 API 获取路由配置
async function fetchRoutes() {
try {
const response = await fetch(‘/api/routes’);
const data = await response.json();

// 转换 API 数据为路由配置
const dynamicRoutes = data.map(item => ({
path: item.path,
element: item.component,
props: item.props,
}));

setRoutes(dynamicRoutes);
} catch (error) {
console.error(‘Failed to fetch routes:’, error);
} finally {
setLoading(false);
}
}

fetchRoutes();
}, []);

if (loading) {
return

Loading routes…

;
}

return (

{routes.map((route, index) => (

))}

);
}
基于用户角色的动态路由
// RoleBasedRoutes.jsx
import { useEffect, useState } from ‘react’;
import { Routes, Route, Navigate } from ‘react-router-dom’;
import { useAuth } from ‘./AuthContext’;

// 组件映射表
const COMPONENT_MAP = {
Dashboard: () => import(‘./pages/Dashboard’),
AdminPanel: () => import(‘./pages/AdminPanel’),
Settings: () => import(‘./pages/Settings’),
Profile: () => import(‘./pages/Profile’),
UserList: () => import(‘./pages/UserList’),
};

function RoleBasedRoutes() {
const { user, loading } = useAuth();
const [routeConfig, setRouteConfig] = useState([]);

useEffect(() => {
if (!user) return;

// 根据角色定义路由配置
const getRoutesForRole = (role) => {
const baseRoutes = [
{ path: ‘/dashboard’, component: ‘Dashboard’, exact: true },
{ path: ‘/profile’, component: ‘Profile’, exact: true },
];

const adminRoutes = [
{ path: ‘/admin’, component: ‘AdminPanel’, exact: true },
{ path: ‘/users’, component: ‘UserList’, exact: true },
{ path: ‘/settings’, component: ‘Settings’, exact: true },
];

const routes = […baseRoutes];
if (role === ‘ADMIN’) {
routes.push(…adminRoutes);
}

return routes;
};

const config = getRoutesForRole(user.role);
setRouteConfig(config);
}, [user]);

if (loading) {
return

Loading…

;
}

if (!user) {
return ;
}

return (

{routeConfig.map((route) => (
Loading component…

}>


}
/>
))}
} />

);
}

// 动态组件加载器
function DynamicComponent({ componentName }) {
const Component = COMPONENT_MAP[componentName];
const [ComponentModule, setComponentModule] = useState(null);

useEffect(() => {
if (Component) {
Component().then(module => {
setComponentModule(module.default);
});
}
}, [Component]);

if (!ComponentModule) {
return

Loading component…

;
}

return ;
}
使用 React Router 的 loader 和 action(v6.4+)
// React Router v6.4+ 新特性:loader 和 action
import {
createBrowserRouter,
RouterProvider,
useLoaderData,
useActionData,
redirect,
} from ‘react-router-dom’;

// Loader – 在路由渲染前加载数据
async function userLoader({ params }) {
try {
const response = await fetch(`/api/users/${params.id}`);
if (!response.ok) {
throw new Error(‘User not found’);
}
return await response.json();
} catch (error) {
throw new Response(‘User not found’, { status: 404 });
}
}

// Action – 处理表单提交和数据变更
async function userAction({ request, params }) {
const formData = await request.formData();
const updates = Object.fromEntries(formData);

try {
const response = await fetch(`/api/users/${params.id}`, {
method: ‘PATCH’,
body: JSON.stringify(updates),
headers: { ‘Content-Type’: ‘application/json’ },
});

if (!response.ok) {
throw new Error(‘Update failed’);
}

return redirect(`/users/${params.id}`);
} catch (error) {
return { error: error.message };
}
}

// 路由配置
const router = createBrowserRouter([
{
path: ‘/’,
element: ,
children: [
{
path: ‘users’,
element: ,
loader: async () => {
const response = await fetch(‘/api/users’);
return response.json();
},
},
{
path: ‘users/:id’,
element: ,
loader: userLoader,
action: userAction,
errorElement: ,
},
{
path: ‘users/:id/edit’,
element: ,
loader: userLoader,
},
],
},
]);

// 使用 RouterProvider
function App() {
return ;
}

// 在组件中使用 loader 数据
function UserProfile() {
const user = useLoaderData();
const actionData = useActionData();

return (

{user.name}

{user.email}

{actionData?.error && (

{actionData.error}

)}




);
}
高级导航功能
useNavigate Hook
import { useNavigate, useLocation } from ‘react-router-dom’;

function NavigationExample() {
const navigate = useNavigate();
const location = useLocation();

const handleNavigation = () => {
// 基本导航
navigate(‘/dashboard’);

// 带状态的导航
navigate(‘/profile’, {
state: {
from: location.pathname,
message: ‘Welcome back!’
}
});

// 替换当前历史记录
navigate(‘/login’, { replace: true });

// 后退
navigate(-1); // 后退一页
navigate(-2); // 后退两页

// 前进
navigate(1); // 前进一页
};

return (




);
}
useNavigation Hook(v6.4+)
import { useNavigation } from ‘react-router-dom’;

function SubmitButton() {
const navigation = useNavigation();

const isSubmitting = navigation.state === ‘submitting’;

return (

);
}

function LoadingIndicator() {
const navigation = useNavigation();

return (

{navigation.state === ‘loading’ && (

正在加载 {navigation.location.pathname}…

)}

);
}
链接组件和 NavLink
import { Link, NavLink, useSearchParams } from ‘react-router-dom’;

function NavigationComponents() {
// 普通链接
return (

);
}

// 高级 NavLink 示例
function AdvancedNavLink() {
return (

);
}
实战项目:带权限管理的博客系统
项目结构
src/
├── components/
│ ├── Layout.jsx
│ ├── PrivateRoute.jsx
│ ├── AuthRoute.jsx
│ └── Loading.jsx
├── pages/
│ ├── Home.jsx
│ ├── Login.jsx
│ ├── Dashboard.jsx
│ ├── BlogList.jsx
│ ├── BlogDetail.jsx
│ ├── BlogEdit.jsx
│ ├── AdminPanel.jsx
│ └── Profile.jsx
├── contexts/
│ └── AuthContext.jsx
├── hooks/
│ └── useAuth.js
├── utils/
│ └── permissions.js
└── App.jsx
完整的路由配置
// App.jsx – 完整的博客系统路由配置
import React from ‘react’;
import {
BrowserRouter,
Routes,
Route,
Navigate,
Outlet,
} from ‘react-router-dom’;
import { AuthProvider, useAuth } from ‘./contexts/AuthContext’;
import PrivateRoute from ‘./components/PrivateRoute’;
import AuthRoute from ‘./components/AuthRoute’;
import Layout from ‘./components/Layout’;

// 页面组件(使用懒加载)
const Home = React.lazy(() => import(‘./pages/Home’));
const Login = React.lazy(() => import(‘./pages/Login’));
const Dashboard = React.lazy(() => import(‘./pages/Dashboard’));
const BlogList = React.lazy(() => import(‘./pages/BlogList’));
const BlogDetail = React.lazy(() => import(‘./pages/BlogDetail’));
const BlogEdit = React.lazy(() => import(‘./pages/BlogEdit’));
const AdminPanel = React.lazy(() => import(‘./pages/AdminPanel’));
const Profile = React.lazy(() => import(‘./pages/Profile’));
const NotFound = React.lazy(() => import(‘./pages/NotFound’));

// 博客布局组件
function BlogLayout() {
return (

我的博客




);
}

// 博客导航组件
function BlogNavigation() {
const { user, logout } = useAuth();

return (

);
}

// 主应用路由
function AppRoutes() {
return (
Loading…

}>

{/* 公共路由 */}
}>
} />
} />

{/* 博客相关路由 */}
}>
} />
} />

{/* 需要登录的博客操作 */}



}
/>



}
/>

{/* 用户仪表板 */}



}
/>




}
/>

{/* 管理员路由 */}



}
/>

{/* 404 */}
} />



);
}

// 应用根组件
function App() {
return (





);
}

export default App;
博客页面组件示例
// pages/BlogList.jsx – 博客列表页面
import { useEffect, useState } from ‘react’;
import { Link, useSearchParams } from ‘react-router-dom’;
import { useAuth } from ‘../contexts/AuthContext’;

function BlogList() {
const [blogs, setBlogs] = useState([]);
const [loading, setLoading] = useState(true);
const [searchParams] = useSearchParams();
const { user } = useAuth();

const category = searchParams.get(‘category’);
const page = searchParams.get(‘page’) || 1;

useEffect(() => {
async function fetchBlogs() {
setLoading(true);
try {
const query = new URLSearchParams({
page,
…(category && { category }),
});

const response = await fetch(`/api/blogs?${query}`);
const data = await response.json();
setBlogs(data);
} catch (error) {
console.error(‘Failed to fetch blogs:’, error);
} finally {
setLoading(false);
}
}

fetchBlogs();
}, [category, page]);

if (loading) return

加载中…

;

return (

博客列表

{user && (

创建博客

)}

{blogs.map(blog => (

{blog.title}

{blog.excerpt}

作者: {blog.author}
|
分类: {blog.category}
|
{new Date(blog.createdAt).toLocaleDateString()}

{user && (

编辑

)}

))}

{/* 分页导航 */}

{page > 1 && (

上一页

)}
第 {page} 页

下一页

);
}

export default BlogList;
// pages/BlogDetail.jsx – 博客详情页面
import { useEffect, useState } from ‘react’;
import { useParams, Link, useNavigate } from ‘react-router-dom’;
import { useAuth } from ‘../contexts/AuthContext’;

function BlogDetail() {
const { id } = useParams();
const navigate = useNavigate();
const { user } = useAuth();
const [blog, setBlog] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
async function fetchBlog() {
setLoading(true);
try {
const response = await fetch(`/api/blogs/${id}`);
if (!response.ok) {
throw new Error(‘Blog not found’);
}
const data = await response.json();
setBlog(data);
} catch (error) {
console.error(‘Failed to fetch blog:’, error);
navigate(‘/blogs’, { replace: true });
} finally {
setLoading(false);
}
}

if (id) {
fetchBlog();
}
}, [id, navigate]);

const handleDelete = async () => {
if (!window.confirm(‘确定要删除这篇博客吗?’)) return;

try {
const response = await fetch(`/api/blogs/${id}`, {
method: ‘DELETE’,
});

if (response.ok) {
navigate(‘/blogs’, {
state: { message: ‘博客已删除’ },
replace: true
});
}
} catch (error) {
console.error(‘删除失败:’, error);
}
};

if (loading) return

加载中…

;
if (!blog) return

博客不存在

;

return (

{blog.title}

作者: {blog.author} |
分类: {blog.category} |
{new Date(blog.createdAt).toLocaleDateString()}

);
}

export default BlogDetail;
// pages/BlogEdit.jsx – 博客编辑/创建页面
import { useState, useEffect } from ‘react’;
import { useParams, useNavigate } from ‘react-router-dom’;
import { useAuth } from ‘../contexts/AuthContext’;

function BlogEdit() {
const { id } = useParams();
const navigate = useNavigate();
const { user } = useAuth();

const [formData, setFormData] = useState({
title: ”,
content: ”,
category: ”,
excerpt: ”,
});
const [loading, setLoading] = useState(false);
const [errors, setErrors] = useState({});

const isEditMode = Boolean(id);

useEffect(() => {
if (isEditMode) {
async function fetchBlog() {
setLoading(true);
try {
const response = await fetch(`/api/blogs/${id}`);
if (!response.ok) throw new Error(‘Blog not found’);

const data = await response.json();

// 权限检查
if (user.role !== ‘ADMIN’ && data.authorId !== user.id) {
navigate(‘/unauthorized’, { replace: true });
return;
}

setFormData({
title: data.title,
content: data.content,
category: data.category,
excerpt: data.excerpt,
});
} catch (error) {
console.error(‘Failed to fetch blog:’, error);
navigate(‘/blogs’, { replace: true });
} finally {
setLoading(false);
}
}

fetchBlog();
}
}, [id, isEditMode, user, navigate]);

const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
…prev,
[name]: value,
}));

// 清除对应字段的错误
if (errors[name]) {
setErrors(prev => {
const newErrors = { …prev };
delete newErrors[name];
return newErrors;
});
}
};

const validateForm = () => {
const newErrors = {};

if (!formData.title.trim()) {
newErrors.title = ‘标题不能为空’;
}

if (!formData.content.trim()) {
newErrors.content = ‘内容不能为空’;
}

if (!formData.category.trim()) {
newErrors.category = ‘分类不能为空’;
}

setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};

const handleSubmit = async (e) => {
e.preventDefault();

if (!validateForm()) return;

setLoading(true);

try {
const url = isEditMode ? `/api/blogs/${id}` : ‘/api/blogs’;
const method = isEditMode ? ‘PATCH’ : ‘POST’;

const response = await fetch(url, {
method,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({
…formData,
authorId: user.id,
}),
});

if (!response.ok) {
throw new Error(isEditMode ? ‘更新失败’ : ‘创建失败’);
}

const savedBlog = await response.json();

// 成功后跳转到博客详情页
navigate(`/blogs/${savedBlog.id}`, {
state: { message: isEditMode ? ‘博客已更新’ : ‘博客已创建’ },
replace: true
});
} catch (error) {
console.error(‘保存失败:’, error);
setErrors({ submit: error.message });
} finally {
setLoading(false);
}
};

if (loading && isEditMode) {
return

加载中…

;
}

return (

{isEditMode ? ‘编辑博客’ : ‘创建博客’}

{errors.submit && (

{errors.submit}

)}



{errors.title && {errors.title}}


{errors.category && {errors.category}}