index.tsx 873 B

12345678910111213141516171819202122232425262728
  1. import React from 'react'
  2. export interface AyncModuleLoaderState {
  3. asyncComponent: any
  4. }
  5. export default function AyncModuleLoader(importComponent: any) {
  6. return class AsyncComponent extends React.Component<unknown, AyncModuleLoaderState> {
  7. constructor(props: unknown) {
  8. super(props)
  9. this.state = {
  10. asyncComponent: null
  11. }
  12. }
  13. async componentDidMount() {
  14. if (this.state.asyncComponent) {
  15. return
  16. }
  17. const { default: component } = await importComponent()
  18. this.setState({
  19. asyncComponent: component
  20. })
  21. }
  22. render() {
  23. const { asyncComponent:Component } = this.state
  24. return Component ? <Component {...this.props} /> : null
  25. }
  26. }
  27. }