# React Router v6 配置完整指南
# 目录
# 1. 基础配置
# 1.1 安装依赖
# 基础依赖
npm install react-router-dom
# TypeScript 类型
npm install -D @types/react-router-dom
# 1.2 基本路由设置
// src/router/index.tsx
import { createBrowserRouter } from "react-router-dom";
import { lazy, Suspense } from "react";
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
path: "home",
element: <Home />
}
]
}
]);
export default router;
# 1.3 在应用中使用
// src/App.tsx
import { RouterProvider } from "react-router-dom";
import router from "./router";
const App = () => {
return <RouterProvider router={router} />;
};
# 2. 路由类型
# 2.1 常见路由类型
// 1. 基础路由
{
path: "/home",
element: <Home />
}
// 2. 嵌套路由
{
path: "/user",
element: <UserLayout />,
children: [
{
path: "profile",
element: <UserProfile />
}
]
}
// 3. 动态路由
{
path: "/user/:id",
element: <UserDetail />
}
// 4. 索引路由
{
index: true,
element: <Home />
}
// 5. 通配符路由
{
path: "*",
element: <NotFound />
}
# 2.2 路由参数
// 路由定义
{
path: "/user/:id",
element: <UserDetail />
}
// 在组件中使用
import { useParams } from 'react-router-dom';
const UserDetail = () => {
const { id } = useParams();
return <div>User ID: {id}</div>;
};
# 3. 路由配置方式
# 3.1 基础配置结构
// src/router/index.tsx
import { createBrowserRouter, Navigate } from "react-router-dom";
import { lazy, Suspense } from "react";
// 懒加载组件
const Home = lazy(() => import("@/pages/home"));
const About = lazy(() => import("@/pages/about"));
const NotFound = lazy(() => import("@/pages/404"));
// Loading 组件
const LoadingComponent = () => (
<div className="loading">Loading...</div>
);
// 路由配置
export const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
index: true,
element: <Navigate to="/home" replace />
},
{
path: "home",
element: (
<Suspense fallback={<LoadingComponent />}>
<Home />
</Suspense>
)
}
]
}
]);
# 3.2 路由元信息
interface RouteObject {
path?: string;
element?: React.ReactNode;
children?: RouteObject[];
meta?: {
title?: string;
requiresAuth?: boolean;
roles?: string[];
};
}
const routes: RouteObject[] = [
{
path: "/admin",
element: <Admin />,
meta: {
requiresAuth: true,
roles: ["admin"]
}
}
];
# 4. 路由功能
# 4.1 导航功能
// 1. 声明式导航
import { Link, NavLink } from 'react-router-dom';
<Link to="/about">关于</Link>
<NavLink
to="/home"
className={({ isActive }) => isActive ? "active" : ""}
>
首页
</NavLink>
// 2. 编程式导航
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/home');
navigate(-1); // 后退
navigate('/user', { state: { id: 1 } }); // 携带状态
# 4.2 获取路由信息
// 1. 获取参数
import { useParams, useSearchParams } from 'react-router-dom';
const { id } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
const query = searchParams.get('q');
// 2. 获取位置信息
import { useLocation } from 'react-router-dom';
const location = useLocation();
console.log(location.pathname);
console.log(location.search);
console.log(location.state);
# 5. 路由守卫
# 5.1 基本认证守卫
const AuthGuard = ({ children }: { children: React.ReactNode }) => {
const { isAuthenticated } = useAuth();
const location = useLocation();
if (!isAuthenticated) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
};
// 使用
{
path: "protected",
element: (
<AuthGuard>
<ProtectedPage />
</AuthGuard>
)
}
# 5.2 角色权限守卫
const RoleGuard = ({
children,
allowedRoles
}: {
children: React.ReactNode;
allowedRoles: string[];
}) => {
const { user } = useAuth();
if (!allowedRoles.includes(user?.role)) {
return <Navigate to="/unauthorized" replace />;
}
return children;
};
# 6. 最佳实践
# 6.1 路由懒加载
// 1. 基本懒加载
const Home = lazy(() => import("@/pages/home"));
// 2. 带预加载的懒加载
const About = lazy(() => import("@/pages/about"));
const prefetchAbout = () => import("@/pages/about");
// 在合适的时机预加载
onMouseEnter={() => {
prefetchAbout();
}}
# 6.2 类型安全
// 路由参数类型
type RouteParams = {
userId: string;
tab: 'profile' | 'settings';
};
const UserPage = () => {
const { userId, tab } = useParams<RouteParams>();
};
// 路由配置类型
interface AppRouteObject extends RouteObject {
meta?: {
title: string;
requiresAuth?: boolean;
roles?: string[];
};
children?: AppRouteObject[];
}
# 7. 常见问题
# 7.1 路由刷新 404
# Nginx 配置
location / {
try_files $uri $uri/ /index.html;
}
# 7.2 路由传参
// 1. URL 参数
navigate(`/user/${userId}`);
// 2. 查询参数
navigate({
pathname: '/search',
search: `?q=${searchTerm}`
});
// 3. 状态传递
navigate('/user', { state: { id: 1 } });
# 7.3 路由过渡
import { CSSTransition, TransitionGroup } from 'react-transition-group';
function App() {
const location = useLocation();
return (
<TransitionGroup>
<CSSTransition
key={location.key}
timeout={300}
classNames="page"
>
<Routes location={location}>
{/* 路由配置 */}
</Routes>
</CSSTransition>
</TransitionGroup>
);
}
# 8. 示例代码
# 8.1 完整的路由配置示例
// src/router/index.tsx
import { createBrowserRouter, Navigate } from "react-router-dom";
import { lazy, Suspense } from "react";
import Layout from "@/layout";
// 懒加载组件
const Home = lazy(() => import("@/pages/home"));
const About = lazy(() => import("@/pages/about"));
const NotFound = lazy(() => import("@/pages/404"));
// Loading 组件
const LoadingComponent = () => (
<div className="flex items-center justify-center min-h-screen">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
</div>
);
// 路由配置
export const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
index: true,
element: <Navigate to="/home" replace />
},
{
path: "home",
element: (
<Suspense fallback={<LoadingComponent />}>
<Home />
</Suspense>
),
meta: {
title: "首页"
}
},
{
path: "about",
element: (
<Suspense fallback={<LoadingComponent />}>
<About />
</Suspense>
),
meta: {
title: "关于"
}
},
{
path: "*",
element: (
<Suspense fallback={<LoadingComponent />}>
<NotFound />
</Suspense>
),
meta: {
title: "404"
}
}
]
}
]);
记住,在配置和使用 React Router 时:
- 总是使用懒加载来优化性能
- 实现适当的加载状态和错误边界
- 使用类型系统保证类型安全
- 实现必要的路由守卫来保护路由
- 遵循最佳实践来组织路由配置
需要更详细的解释或有其他问题吗?