我具有以下功能:
const withCacheRefresh = (lazyLoadComponent: any) => {
return new Promise<React.ComponentType<any>>((resolve) => {
lazyLoadComponent()
.then(resolve)
.catch(() => {
window.location.reload(true);
});
});
}
[以承诺作为参数,特别是lazy。我继续称呼诺言,或者通过返回lazy
的结果来解决诺言,或者在我的捕获中刷新页面。我遇到以下Typescript编译错误的问题:
Type 'Promise<ComponentType<any>>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.
Type 'ComponentType<any>' is not assignable to type '{ default: ComponentType<any>; }'.
Property 'default' is missing in type 'ComponentClass<any, any>' but required in type '{ default: ComponentType<any>; }'. TS2322
我有两个问题:
我如何将我的第一个参数lazyLoadComponent
指定为返回React.Component<any>
类型的组件而不是仅返回any
的函数的类型?
如何固定我的Promise<React.ComponentType<any>>
定义,使其符合所需的Promise<{ default: ComponentType<any>; }>
类型?
更新
[我收到的答案告诉我,对于所陈述的问题,我的解决方案是不正确的,但我故意选择省略有关较大问题空间细微差别的详细信息。
自被问到以来,我感到很容易澄清:当为我的应用程序发布新的部署时,将创建新的块,并从生产工作空间中清除旧的块。因此,仍保留在先前发行版中的客户端(因为尚未将应用程序刷新到最新版本)仍在使用旧块。 HMR无法正常运行,因为这是一个production环境。显式刷新将导致服务工作者检索最新的块。
[Github Issue中描述了类似情况。
我将假定您有其他原因导致页面重新加载,而不是“我希望它可以解决该错误”(如果这是原因,或者出于缓存清除目的,则绝对应尝试[ C0])。
EDIT由于OP已经阐明了他的意思,所以我建议不要在浏览器中不缓存延迟加载的组件,而应在Service Worker本身中使用预缓存清单,这将允许SW会在重新生成新清单时加载清单。 HMR了解更多信息。
我还将假设您想将此功能与See this question一起使用,而不是在lazy
上调用它,因为否则无法完全捕获任何错误。lazy
没有必要将其包装在诺言中,因为它已经是。您可以直接在其上点击
用法:import React from 'react'; type LazyFactory = Parameters<typeof React.lazy>[0]; const withCacheRefresh = ( importResult: LazyFactory ): LazyFactory => () => importResult().catch(() => { window.location.reload(true); // Following makes return type `never`, which satisfies TypeScript throw new Error('component load failed'); });
。
.catch