React中实现页面切换的深度指南:从基础到高级实践
一、React Router核心概念解析
1.1 路由工作原理深度剖析
在单页面应用(SPA)中,路由系统通过以下机制实现无刷新跳转:
// 伪代码示意
class Router {
constructor(routes) {
this.routes = routes;
window.addEventListener('hashchange', this.handleHashChange);
}
handleHashChange = () => {
const currentHash = window.location.hash.slice(1);
const matchedRoute = this.routes.find(route =>
pathToRegexp(route.path).test(currentHash)
);
this.renderComponent(matchedRoute.component);
}
}
1.2 React Router v6 核心API对比
API | 作用 | v5对比 |
---|---|---|
<BrowserRouter> |
使用HTML5 history API的路由器 | 同v5 |
<Routes> |
路由容器组件 | 替代<Switch> |
useNavigate() |
编程式导航Hook | 替代useHistory() |
<Outlet> |
嵌套路由占位符 | 替代props.children |
useParams() |
获取URL参数 | 同v5 |
二、基础路由实现详解
2.1 完整项目配置步骤
- 安装依赖
npm install react-router-dom@6
- 路由配置文件
// src/routes/config.js
export const routeConfig = [
{
path: "/",
element: <HomePage />,
meta: {
title: "首页"
}
},
{
path: "/products",
element: <ProductList />,
children: [
{
path: ":id",
element: <ProductDetail />
}
]
}
];
- 路由初始化
// src/App.jsx
import { useRoutes } from 'react-router-dom';
function App() {
const element = useRoutes(routeConfig);
return (
<BrowserRouter>
<PageHeader />
{element}
<PageFooter />
</BrowserRouter>
);
}
2.2 按钮跳转的三种实现方式
方式1:使用Link组件
import { Link } from 'react-router-dom';
<Link to="/about" state={
{ fromDashboard: true }}>
<Button variant="primary">关于我们</Button>
</Link>
方式2:编程式导航
function HomeButton() {
const navigate = useNavigate();
return (
<button
onClick={() => {
navigate('/about', {
state: { timestamp: Date.now() },
replace: false
});
}}
>
跳转
</button>
);
}
方式3:表单提交导航
<Form method="post" action="/search">
<input type="text" name="keyword" />
<button type="submit">搜索</button>
</Form>
三、参数传递的进阶用法
3.1 URL参数的完整处理流程
- 带参数路由配置
<Route path="/user/:userId/post/:postId" element={<UserPost />} />
- 参数类型转换中间件
// src/utils/routeParams.js
export const parseRouteParams = (params) => {
return Object.fromEntries(
Object.entries(params).map(([key, value]) => {
if (/^\d+$/.test(value)) return [key, Number(value)];
if (value === 'true') return [key, true];
if (value === 'false') return [key, false];
return [key, value];
})
);
};
// 组件中使用
const rawParams = useParams();
const params = parseRouteParams(rawParams);
3.2 状态参数的安全使用
典型应用场景:
• 跨页面传递敏感信息(如临时token)
• 保持页面跳转上下文
• 传递复杂对象(如表单草稿)
状态加密方案:
import AES from 'crypto-js/aes';
const navigate = useNavigate();
const secureNavigate = (path, state) => {
const encryptedState = AES.encrypt(
JSON.stringify(state),
import.meta.env.VITE_STATE_KEY
).toString();
navigate(path, { state: encryptedState });
};
// 接收端解密
const location = useLocation();
const decryptedState = JSON.parse(
AES.decrypt(
location.state,
import.meta.env.VITE_STATE_KEY
).toString(CryptoJS.enc.Utf8)
);
四、权限控制与路由守卫
4.1 多层次权限系统设计
// src/components/AuthRoute.jsx
const AuthRoute = ({ roles, children }) => {
const { user } = useAuth();
const location = useLocation();
if (!user) {
return <Navigate to="/login" state={
{ from: location }} replace />;
}
if (!roles.includes(user.role)) {
return <Navigate to="/403" replace />;
}
return children;
};
// 使用示例
<Route
pat