【问题标题】:Lazy loading: react-loadable is failing to load components in other folders延迟加载:react-loadable 无法加载其他文件夹中的组件
【发布时间】:2018-08-31 19:28:34
【问题描述】:

使用 Create-react-app,我想延迟加载我的一些组件,只要这些组件与我的主要组件(我在其中定义路由)位于同一文件夹中,这一切正常,但是只要我想要从另一个文件夹加载一个组件,比如

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

找不到/导入模块。 (如果我移动文件,完全相同的模块将起作用!

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

  • 我还尝试将路由更改为 src/x/x 而不是 ../x/x,但再次出现错误。

【问题讨论】:

    标签: reactjs lazy-loading react-loadable


    【解决方案1】:

    您使用了错误的路径,请使用以下命令进行更正:

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

    【讨论】:

      【解决方案2】:

      我创建延迟加载组件的方式是通过高阶组件。我创建了一个名为“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;
      

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

      import Exemple from './example/example';
      

      你将使用:

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

      【讨论】:

      • 感谢您的回复,如果您在沙箱中查看我的方法,它非常相似(更动态一点)但是问题在于加载文件位于另一个文件夹中的组件。
      猜你喜欢
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2021-12-06
      • 2020-10-17
      • 2017-09-29
      • 2019-04-23
      • 1970-01-01
      相关资源
      最近更新 更多