延迟加载:react-loadable 无法加载其他文件夹中的组件

Lazy loading: react-loadable is failing to load components in other folders

使用 Create-react-app,我想延迟加载我的一些组件,只要这些组件与我的主要组件(我定义路由的位置)位于同一文件夹中,这就可以正常工作,但是尽快因为我想从另一个文件夹加载组件,例如

loader: () => import("../containers/HomeAContainer")

find/import 模块失败。 (如果我移动文件,完全相同的模块将起作用!

我做了一个完整的例子可以看到here

我创建延迟加载组件的方式是通过高阶组件。我创建了一个名为“asyncComponent”的文件,然后我输入代码:

import React, { Component } from 'react';

const asyncComponent = ( importComponent ) => {
    return class extends Component{
        state = { component: null }

        componentDidMount(){
            importComponent().then(cmp =>{
                this.setState({component: cmp.default});
            });
        }

        render (){
            const C = this.state.component;
            return C ? <C {...this.props} /> : null;
        }
    }
}

export default asyncComponent;

此组件将接收一个函数作为参数,然后 return 您需要的组件。该函数实际上是一个导入函数,其中包含您要延迟加载的组件的路径。 所以不要使用:

import Exemple from './example/example';

您将使用:

import asyncComponent from './asyncComponent';
const asyncExample = asyncComponent(()=>{
    return import('./example/example');
});

您使用的路径有误,请更正:

{ path: "/c", component: "./containers/HomeAContainer" }