react 如何在项目中配置路由
配置路由的基本步骤
在React项目中配置路由需要使用react-router-dom库。安装依赖包:
npm install react-router-dom
导入必要的组件并定义路由结构:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
基本路由配置
在应用入口文件中包裹根组件:
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
</Routes>
</Router>
);
}
嵌套路由实现
使用嵌套路由组织页面层级:
<Route path="/user" element={<UserLayout />}>
<Route index element={<UserDashboard />} />
<Route path="profile" element={<UserProfile />} />
<Route path="settings" element={<UserSettings />} />
</Route>
动态路由参数
通过冒号语法定义动态路由:

<Route path="/products/:id" element={<ProductDetail />} />
在组件中获取参数:
import { useParams } from 'react-router-dom';
const { id } = useParams();
编程式导航
使用useNavigate进行页面跳转:
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/target-path');
路由守卫配置
通过高阶组件实现路由守卫:

const PrivateRoute = ({ children }) => {
const isAuthenticated = checkAuth();
return isAuthenticated ? children : <Navigate to="/login" />;
};
<Route path="/dashboard" element={<PrivateRoute><Dashboard /></PrivateRoute>} />
404页面处理
添加通配路由捕获未匹配路径:
<Route path="*" element={<NotFoundPage />} />
路由懒加载
使用React.lazy实现代码分割:
const AboutPage = React.lazy(() => import('./AboutPage'));
<Suspense fallback={<Loading />}>
<Route path="/about" element={<AboutPage />} />
</Suspense>
路由配置最佳实践
将路由配置抽离为独立文件:
// routes.js
export const routes = [
{ path: '/', element: <HomePage /> },
{ path: '/contact', element: <ContactPage /> }
];
// App.js
{routes.map((route) => (
<Route key={route.path} {...route} />
))}






