[英]Lazy loading: react-loadable is failing to load components in other folders
Using Create-react-app, I want to lazy load some of my components, this is working fine as long as the components are in the same folder as my main component (where I define the routes) however as soon as I want to load a component from another folder like 我想使用Create-react-app延迟加载我的一些组件,只要这些组件与我的主要组件位于同一文件夹中(我在其中定义路由)就可以正常工作,但是只要我想加载来自另一个文件夹的组件,例如
loader: () => import("../containers/HomeAContainer")
it fails to find/import the module. 它找不到/导入模块。 (exact same module will work if I move the file! (如果我移动文件,则完全相同的模块将起作用!
I have made a complete example which can be seen here 我做了一个完整的例子,可以在这里看到
The way i create lazy loading components is through a higher order component. 我创建延迟加载组件的方式是通过一个高阶组件。 I create a file called " asyncComponent ", then i put in the code: 我创建一个名为“ 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;
This component will receive a function as a parameter and then return the component you want. 该组件将接收一个函数作为参数,然后返回所需的组件。 The function is actually a import funcion with the path of your component that you want to lazy load. 该函数实际上是一个导入函数,其中包含您要延迟加载的组件的路径。 So instead of using: 因此,不要使用:
import Exemple from './example/example';
You will use: 您将使用:
import asyncComponent from './asyncComponent';
const asyncExample = asyncComponent(()=>{
return import('./example/example');
});
您使用了错误的路径,请使用以下命令进行更正:
{ path: "/c", component: "./containers/HomeAContainer" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.