方法一:
从右到左,一级一级抛出
方法二:
(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