【问题标题】:How to create module with react components and load with react lazy?如何使用反应组件创建模块并使用反应惰性加载?
【发布时间】:2020-10-01 04:14:44
【问题描述】:

我曾尝试在 react lazy 中加载模块,但它是未定义的组件。

我的模块文件 products/index.js

import Categories from './Category/Categories';
import Brands from './Brand/Brands';   

export default [Categories,Brands];

在路由器文件中我尝试过这样,

const products = React.lazy(() => import('./views/products'));

但是,

console.log(products[0]) // undefined
console.log(products[1]) // undefined

模块文件有问题吗?以及如何通过 Reactlazy 和 Suspense 实现这一点?

【问题讨论】:

  • 这里是 React Lazy 和 Suspense 的 CRA 文档CRA - Doc
  • 您是否在延迟加载的组件周围提供了 Suspense 标签?
  • 是的,我使用了悬念标签

标签: javascript reactjs


【解决方案1】:

这样试试

React.lazy(() => import('./views/products').then(module => ({ default: module.Categories}));

【讨论】:

  • 这不起作用。模块导出需要任何更改吗?
【解决方案2】:

我有一个解决方案,我在 index.js 和 Router.js 文件中进行了更新。

在 products/index.js 文件中

import Categories from './Category/Categories';
import Brands from './Brand/Brands';   

export const modules={Categories : Categories,Brands : Brands};

export default ProductModule = ({ component, path, isPrivate, ...rest }) =>{ 
   let RouteComponent=modules[component];   
   return (<Route path={path} component={RouteComponent}  {...rest}/>);     
}

在 Router.js 中

 const ProductModule = React.lazy(() => import('./views/products'));

然后像这样使用,

  <ProductModule path='/product/brands' component="Brands"/>

所以它工作正常。

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多