- 安装react-router、react-router-dom
npm install react-router@6.3.0 react-router-dom@6.3.0 --save
- 新建路由表文件
import { lazy } from 'react';
import lazyLoad from './lazyLoad';
const Home = lazy(() => import(`@src/pages/home`));
const Login = lazy(() => import(`@src/pages/login`));
const rootRouter = [
{
path: '/',
name: '首页',
redirect: '/basis',
key: '/',
children: [
{
index: true,
name: '首页',
key: '/',
element: lazyLoad(Home),
},
{
index: false,
path: 'login',
name: 'Demo',
key: '/login',
element: lazyLoad(Login),
},
],
},
];
export default rootRouter;
- lazyLoad文件
import React from 'react';
import Loading from '@components/Loading';
export default function lazyLoad(Comp) {
return (
<React.Suspense fallback={<Loading />}>
<Comp />
</React.Suspense>
);
}
- 在app.js中引入
import React from 'react';
import { HashRouter as Router, useRoutes } from 'react-router-dom';
import rootRouter from '@src/router/index';
const AppRoutes = () => useRoutes(rootRouter);
function App() {
return (
<Router>
<AppRoutes />
</Router>
);
}
export default App;