React - Dynamically Import Components

前端 未结 8 1695
别那么骄傲
别那么骄傲 2020-12-05 07:14

I have a page which renders different components based on user input. At the moment, I have hard coded the imports for each component as shown below:

    imp         


        
8条回答
  •  余生分开走
    2020-12-05 08:02

    Here is another solution: We get the list of needed components list = ['c1', 'c2', 'c3']. It may be pulled from json file to an array (i use redux-store so i initiate getting forms by this.props.getForms()). But you may just create and access the list of components manually.

        componentDidMount = () => {
    //we get elements list from any source to redux-store
            this.props.getForms();
    //access redux-store to the list
            const forms = this.props.configBody.sets;
    //make deep object copy
            const updatedState = { ...this.state };
            updatedState.modules = [];
            if (forms) {
    //here is the very dynamic import magic: we map the import list and prepare to store the imports in Component`s state
                const importPromises = forms.map(p =>
                    import(`../TemplateOrders/Template${p.order}`)
                        .then(module => {
                            updatedState.modules.push(module.default)
                        })
                        .catch(errorHandler(p))
                )
    //wait till all imports are getting resolved
                Promise.all(importPromises)
                    .then(res =>
    //then run setState
                        this.setState({ ...updatedState }, () => {
                            console.log(this.state);
                        }))
            }
        }
    
        render() {
            const forms = this.props.configBody.sets;
    //we iterate through the modules and React.createElemet`s 
            const list = this.state.modules
                ? this.state.modules.map((e, i) =>
                    createElement(e, { key: forms[i].title }, null)
                )
                : [];
            return (
                
                    Home
                    

    hello there

    //push them all to get rendered as Components {list.map(e => e)}
    ) }

    So when your app is loaded it pulls the needed modules.

    I thought to use promises to import them, but modules are already promises.

    In case we need to ajax them from server lately, so we need to split the modules before bundling with require (or something like that) dont know exactly.

提交回复
热议问题