Load dynamic component group

The React project needs to load different components according to the back-end return.

Asynchronous component loading

AsyncComponent.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: component
      });
    }

    render() {
      const C = this.state.component;

      return C ? <C {...this.props} /> : null;
    }
  }

  return AsyncComponent;
}

Component list loading

component.js

import React from 'react';
import asyncComponent from './AsyncComponent'

export default class componentList extends React.Component{
    constructor(props) {
        super(props);
       
        this.state = {
          components: null
        };
        
      }

      async componentDidMount() { 
        var items=[]
        var names=['firstComponent','secondComponent']//ajax backend provides the name of loading component
        var context = require.context('../components', true, /\.jsx$/);
        console.log(context.keys());
        for(var i=0;i<names.length;i++)
        {
            let tempName='./'+names[i]+".jsx"
            let TempCom=asyncComponent(()=>context(tempName)) 
            items.push(<TempCom />)
        }

        this.setState({
            components: items
          });
      } 

    render() {
        return (
            <div className="detailWried">
                {this.state.components}
            </div>
        );
      }
}

Use require.context to load variable component name

Because import is executed statically, expressions and variables cannot be used. These syntax structures can only be obtained at run time.

// Report errors
import { 'f' + 'oo' } from 'my_module';

// Report errors
let module = 'my_module';
import { foo } from module;

// Report errors
if (x === 1) {
  import { foo } from 'module1';
} else {
  import { foo } from 'module2';
}

The above three writing methods will report errors because they use expressions, variables and if structures. In the static analysis phase, none of these grammars can get values.

Keywords: React

Added by iffy on Sat, 28 Dec 2019 18:59:48 +0200