react如何封装router
封装 React Router 的基本方法
在 React 中封装 Router 通常是为了统一管理路由配置、添加中间件或增强功能。以下是几种常见的封装方式:
基于 react-router-dom 的路由配置封装
创建一个独立的路由配置文件,集中管理所有路由:
// routes.js
import { Route } from 'react-router-dom';
import HomePage from './pages/Home';
import AboutPage from './pages/About';
export const routes = [
{
path: '/',
exact: true,
component: HomePage
},
{
path: '/about',
component: AboutPage
}
];
// 在 App.js 中使用
import { BrowserRouter as Router, Switch } from 'react-router-dom';
import { routes } from './routes';
function App() {
return (
<Router>
<Switch>
{routes.map((route, i) => (
<Route key={i} {...route} />
))}
</Switch>
</Router>
);
}
创建高阶路由组件
通过高阶组件增强路由功能,例如添加身份验证:
// ProtectedRoute.js
import { Route, Redirect } from 'react-router-dom';
const ProtectedRoute = ({ isAuthenticated, ...props }) => {
return isAuthenticated ? (
<Route {...props} />
) : (
<Redirect to="/login" />
);
};
// 使用示例
<ProtectedRoute
path="/dashboard"
component={Dashboard}
isAuthenticated={userLoggedIn}
/>
动态路由加载封装
结合 React.lazy 实现代码分割和动态加载:
// AsyncRoute.js
import { Suspense } from 'react';
const AsyncRoute = ({ component: Component, ...props }) => (
<Route
{...props}
render={() => (
<Suspense fallback={<div>Loading...</div>}>
<Component />
</Suspense>
)}
/>
);
// 路由配置中使用
const routes = [
{
path: '/settings',
component: React.lazy(() => import('./pages/Settings'))
}
];
路由守卫封装
实现全局路由守卫逻辑:
// RouterGuard.js
import { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
const RouterGuard = ({ children, authCheck }) => {
const history = useHistory();
useEffect(() => {
if (!authCheck()) {
history.push('/unauthorized');
}
}, [history, authCheck]);
return children;
};
// 在根组件中使用
<Router>
<RouterGuard authCheck={() => checkUserPermission()}>
<AppRoutes />
</RouterGuard>
</Router>
TypeScript 路由封装示例
为路由添加类型安全:
// types.ts
interface RouteConfig {
path: string;
component: React.ComponentType;
exact?: boolean;
guards?: Array<() => boolean>;
}
// routes.ts
const routes: RouteConfig[] = [
{
path: '/admin',
component: AdminPanel,
guards: [() => checkAdminRole()]
}
];
这些封装方法可以根据具体需求组合使用,创建出符合项目架构的路由管理系统。关键是根据应用规模选择适当层级的封装,避免过度设计。







