您当前的位置: 首页 > 

【03】

暂无认证

  • 1浏览

    0关注

    196博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

react-router懒加载

【03】 发布时间:2020-08-22 19:26:12 ,浏览量:1

基于封装好的路由

封装过程详见 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 ?  : 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

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

关注
打赏
1657344724
查看更多评论
立即登录/注册

微信扫码登录

0.0376s