如何在 reactJS 中编写一个惰性加载器(带有示例)

Posted

技术标签:

【中文标题】如何在 reactJS 中编写一个惰性加载器(带有示例)【英文标题】:How to typescript a lazy loader in reactJS (with example) 【发布时间】:2021-10-23 18:57:24 【问题描述】:

我正在尝试将此 react js 代码转换为 typescript,但我不确定如何将此代码转换为 typescript

这两行有问题

const Shop = lazy(pageLoader(() => import("pages/report/shop")));
const Item = lazy(pageLoader(() => import("pages/report/item")));

我收到以下错误,我不知道该怎么办

Argument of type '() => Promise<unknown>' is not assignable to parameter of type '() => Promise< default: ComponentType<any>; >'.
  Type 'Promise<unknown>' is not assignable to type 'Promise< default: ComponentType<any>; >'.
    Type 'unknown' is not assignable to type ' default: ComponentType<any>; '.ts(2345)

实用程序

import i18n from "i18n";
import  ComponentType  from "react";

export const pageLoader = (
  component: () => any
) => 
  return () =>
    new Promise((resolve, reject) => 
      component()
        .then((module: React.ReactNode) => resolve(module))
        .catch((error: object) => 
          alert(i18n.t("session_timeout_message"));
          window.location.href = `$process.env.REACT_APP_LOGOUT`;
          reject(error);
        );
    );
;

报告

import  lazy, Suspense  from "react";
import  Switch, Route  from "react-router-dom";

import  PulseDotLoader  from "components/Loader";
import  pageLoader  from "components/Pages/utils";

const Shop = lazy(pageLoader(() => import("pages/report/shop")));
const Item = lazy(pageLoader(() => import("pages/report/item")));

const Report = () => 
  return (
    <Suspense fallback=<PulseDotLoader size=20 verticalPosition="50%" />>
      <Switch>
        <Route path="/report/shop" component=Shop />
        <Route path="/report/item" component=Item />
      </Switch>
    </Suspense>
  );
;

export default Report;

【问题讨论】:

【参考方案1】:

错误信息很直观,一个工作示例:

"typescript": "^4.4.2",
"react": "^16.14.0"

utils.ts:

import  ComponentType  from "react";

export const pageLoader = (
  loadComponent: () => Promise< default: ComponentType<any> >
) => 
  return (): Promise< default: ComponentType<any> > =>
    new Promise((resolve, reject) => 
      loadComponent()
        .then((module) => resolve(module))
        .catch((error: object) => 
          reject(error);
        );
    );
;

report.ts:

import  lazy  from "react";
import  pageLoader  from "./utils";

const Shop = lazy(pageLoader(() => import("./shop")));
const Item = lazy(pageLoader(() => import("./item")));

shop.tsx:

import React from "react";

export default function Shop() 
  return <div>shop</div>;

item.tsx:

import React from "react";

export default function Item() 
  return <div>item</div>;

【讨论】:

以上是关于如何在 reactJS 中编写一个惰性加载器(带有示例)的主要内容,如果未能解决你的问题,请参考以下文章

如何使用惰性加载器捕获 Capybara Feature JS 测试的服务器端错误?

带有禁用日期的 ReactJS 日期范围选择器 - Rsuite

带有 React JS/Polymer 的主题 css 选择器

ReactJs - 将带有嵌套 React 组件的原始 HTML 转换为 JSX

Kendo UI:Kendo 网格的惰性绑定

ReactJS:在superagent ajax请求期间显示带有加载消息的模态