方法一:
从右到左,一级一级抛出
 react 路由按需加载

 

 


方法二:
(1)router文件夹asyncComponent.jsx创建文件
(2)填写内容
(3)router文件夹的index文件引入asyncComponent.jsx

react 路由按需加载

  asyncComponent.jsx文件内容(JS版):

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

asyncComponent.tsx文件内容(TS版):

import React, { Component, ComponentType } from 'react';
function asyncComponent<T>(importComponent: () => Promise<{ default: ComponentType<T> }>) {
  return class extends Component<T> {
    state: { component: ComponentType<T> | null }
    constructor(props: T) {
      super(props);
      this.state = {
        component: null
      }
    }
    async componentDidMount() {
      const { default: component } = await importComponent()
      this.setState(component)
    }
    render() {
      const C = this.state.component;
      return C ? <C {...this.props} /> : null;
    }
  }
};
export default asyncComponent

 

相关文章:

  • 2022-12-23
  • 2021-09-16
  • 2022-02-18
  • 2021-06-15
  • 2021-06-14
  • 2021-08-05
  • 2022-12-23
猜你喜欢
  • 2018-10-31
  • 2021-12-14
  • 2022-12-23
  • 2021-11-13
  • 2021-04-03
  • 2022-12-23
  • 2022-01-01
相关资源
相似解决方案