原创

react-router懒加载


基于封装好的路由

封装过程详见 https://web03.cn/blog/151

asyncComponent.jsx

import React,{Component} from 'react'
export default function asyncComponent(importantComponent) {
  class AsyncComponent extends Component{
    constructor(props){
      super(props);
      this.state={
        component: null
      }
    }
    componentDidMount() {
      importantComponent().then((mod)=>{
        this.setState({
          component: mod.default || mod
        })
      })
    }
    render (){
      const C = this.state.component
      return C ? <C {...this.props}/> : null
    }
  }
  return AsyncComponent
}

router.js

import AsyncComponent from '../component/router/asyncComponent'
// import Index from '../pages/Index'
const Index = AsyncComponent(()=>import('../pages/Index'));
// import Home from '../pages/Home'
const Home = AsyncComponent(()=>import('../pages/Home'));
// import User from '../pages/User'
const User = AsyncComponent(()=>import('../pages/User'));
// import NotFond from '../pages/other/NotFond'
const NotFond = AsyncComponent(()=>import('../pages/other/NotFond'))
// import ReduxTest from '../pages/test/ReduxTest'
const ReduxTest = AsyncComponent(()=>import('../pages/test/ReduxTest'))
// import AntdTest from '../pages/test/AntdTest'
const AntdTest = AsyncComponent(()=>import('../pages/test/AntdTest'))
const router = [
  {
    path: '/index',//首页默认加载的页面
    componentName: Index,
    exact: false, //是否为严格模式 默认true。注意:本次封装对于有子路由的,exact一律设置为false(详见App.js匹配规则)
    routes: [
      {
        path: '/index/home',
        componentName: Home
      },
      {
        path: '/index/user',
        componentName: User
      }
    ]
  },
  {
    path: '/redux-test',
    componentName: ReduxTest
  },
  {
    path: '/antd-test',
    componentName: AntdTest
  },
  {
    path: '/404',
    componentName: NotFond
  },
];
export default router

懒加载配置完成,查看打包文件,每个路由都会被单独打包成文件
进入路由再加载需要的路由文件

react
  • 作者:零三(联系作者)
  • 最后更新时间:2020-08-19 14:59
  • 版权声明:自由转载-非商用-非衍生-保持署名
  • 转载声明:来源地址 https://web03.cn