react 路由按需加载


方法一:
从右到左,一级一级抛出
 

 

 


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

  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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM