react-router-domv4.1.2版本,不能识别 React.lazy这种最新的懒加载方式
直接在 Route上使用会报错,会报错

LazyLoad.js

  1. import React, { lazy, Suspense } from 'react';
  2. import Loading from './Loading';
  3. // import Home from './views/Home';
  4. const List = lazy(() => import('./views/Home')) // 返回一个 Promise
  5. function App() {
  6. return (
  7. <Suspense fallback={<Loading />}>
  8. <List />
  9. </Suspense>
  10. )
  11. }

lazy组件封装

components/lazy.js

  1. import React, { lazy, Suspense } from 'react';
  2. import Loading from './Loading';
  3. const List = lazy(() => import('./views/Home')) // 返回一个 Promise
  4. function App(props) {
  5. const {component, ...args } = props
  6. let LAZY
  7. if (!component || component.constructor.name !== 'Promise') {
  8. LAZY = import('./error')
  9. }
  10. LAZY = lazy(() => {
  11. return new Promise(resolve => {
  12. resolve(component)
  13. })
  14. })
  15. return (
  16. <Suspense fallback={<Loading />}>
  17. <LAZY {...args}/>
  18. </Suspense>
  19. )
  20. }

路由router.js 中使用

  1. import LazyLoad from '@/component/lazy';
  2. function App() {
  3. return (
  4. <div>
  5. <LazyLoad component={import('./views/List')}/>
  6. </div>
  7. )
  8. }