https://www.npmjs.com/package/react-router-config
这是我的目录,router文件 index.js 就是我的路由文件。 assembly 是引入组件的地方,那里配了懒加载
第一步: 安装
npm install --save react-router-config
第二步: 外面 index.js 引入
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux' import { persistStore } from 'redux-persist' import { PersistGate } from 'redux-persist/lib/integration/react'; import { renderRoutes } from "react-router-config"; import { BrowserRouter } from "react-router-dom"; import { store } from '@/store' import routes from '@/router'; //引入路由文件 ReactDOM.render( <Provider store={store}> {/* redux */} <PersistGate loading={null} persistor={persistStore(store)}> {/* 数据持久化 */} <BrowserRouter> {/* 路由 */} {renderRoutes(routes)} </BrowserRouter> </PersistGate> </Provider>, document.getElementById('root') )
第三步: router index.js 文件
import { Home, Errors, Children01, Children02 } from './assembly'; const routes = [ { path: '/404', component: Errors }, //嵌套路由 { path: '/home', component: Home, routes: [ { path: "/home/01", component: Children01 }, { path: "/home/02", component: Children02 }, ] }, ] export default routes
第四步: home页面渲染子路由
import React, { Component } from 'react' import { renderRoutes } from 'react-router-config'; import { Link } from "react-router-dom"; export default class Home extends Component { render() { const { routes } = this.props.route return ( <div> <Link to='/home/01'>页面1</Link> <Link to='/home/02'>页面2</Link> {renderRoutes(routes)} //渲染子路由 </div> ) } }