上代码 改造src/router/index.js
import React from 'react' import {BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom' import routes from './route' class IRouter extends React.Component{ render(){ return ( <Router> <Switch> {/* 开始改造 */} { routes.map((router, key) => { if(undefined !== router.children && router.children.length){ return (<Route key={key} path={router.path} exact={router.exact} component={(props) => { return (<router.component> { router.children.map((children, key2) => { return <Route path={children.path} key={key2} exact={children.exact} {...props} component={children.component} /> }) } </router.component>) }} />) }else{ return (<Route key={key} path={router.path} exact={router.exact} component={router.component} />) } }) } {/* 改造前 */} {/* <Route path="/login" component={Login} /> <Route path="/" component={(props) => { return <Home> <Route path="/board" {...props} exact component={Board} /> </Home> }} /> 404页面 <Route path="*" component={NotFound} /> */} </Switch> <li><Link to="/">Home</Link></li> <li><Link to="/login" >Login</Link></li> <li><Link to="/board" >board</Link></li> </Router> ) } } export default IRouter新增 src/router/route.js 用于配置路由
import Loadable from 'react-loadable' import React from 'react' import NotFound from '../pages/NotFound/NotFound' function Loading(){ return <div>Loading</div> } const Home = Loadable({ loading: Loading, loader: () => import('../pages/Home/Home') }); const Login = Loadable({ loading: Loading, loader: () => import('../pages/Login/Login') }); const Board = Loadable({ loading: Loading, loader: () => import('../pages/Board/Board') }); const routes = [ { path: '/login', exact: false, component: Login }, { path: '/', exact: false, component: Home, children: [ { path: '/board', exact: true, component: Board } ] }, { path: '*', exact: false, component: NotFound } ] export default routes;其他文件没有变动 这样只要修改src/router/route.js就可以修改路由配置了 便于以后的维护
这样就可以拥有一个便于维护的路由配置了 当然这只是基础的内容,后续可以根据自己的需求进行添加响应配置, 接下来开始学习路由监听与拦截