学习目标:
提示:路由封装和路由高级封装
(1) 路由封装
将一级路由,通过router/RouterView.jsx
组件进行封装
新建router目录,在目录下新建RouterView.jsx
/**
* 路由封装
*/
import {lazy, Suspense} from "react"
import {Redirect, Route, Switch} from "react-router-dom"
//使用懒加载 导入一级路由
const Layout = lazy(() =>import("../views/pages/Layout"))
const Login = lazy(() =>import("../views/pages/Login"))
const Reg = lazy(() =>import("../views/pages/Reg"))
const NotFound = lazy(() =>import("../views/pages/NotFound"))
//使用懒加载 导入二级级路由
const About = lazy(() =>import("../views/pages/About"))
const Home = lazy(() =>import("../views/pages/Home"))
const UCenter = lazy(() =>import("../views/pages/UCenter"))
const Brands = lazy(() =>import("../views/pages/Brands"))
// 封装路由
const routes = [
// 配置一级路由
{
path: "/",
redirect:"/login",
exact: true
},
{
path: "/login",
component: Login,
exact: false
},
{
path: "/reg",
component: Reg,
exact: false
},
{
path: "/layout",
component: Layout,
exact: false,
// 配置二级路由
children: [
{
path: "/layout/Brands",
component: Brands,
exact: false
},
{
path: "/layout/UCenter",
component: UCenter,
exact: false
},
{
path: "/layout/about",
component: About,
exact: false
},
{
path: "/layout/home",
component: Home,
exact: false
}
]
},
// 找不到路径的时候 进行匹配
{
path: "*",
component: NotFound,
exact: false
}
]
// 导出
export default function RouterView() {
return <Suspense fallback="loading">
<Switch>
{
routes.map(route => {
if (route.redirect) {
return <Route key={route.path}
path={route.path}
exact={route.exact}
>
<Redirect to={route.redirect}/>
</Route>
} else {
return <Route key={route.path}
path={route.path}
exact={route.exact}
component={route.component}
>
</Route>
}
})}
</Switch>
</Suspense>
}
App.jsx
中添加一级路由:
import './App.css';
// 引入页面组件
import {BrowserRouter as Router, NavLink} from "react-router-dom"
import RouterView from "./router/RouterView";
function App() {
return (
<div className="App">
<Router>
{/*页面导航*/}
<nav>
<span><NavLink to="/" exact>LOGO</NavLink></span>
<span><NavLink to