在 TypeScript 中使用 React.lazy [英] Using React.lazy with TypeScript

查看:67
本文介绍了在 TypeScript 中使用 React.lazy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 TypeScript React 应用程序中使用 React.lazy 进行代码拆分.

I am trying to use React.lazy for code splitting in my TypeScript React app.

我所做的就是改变那条线:

All I am doing is changing that line:

import {ScreensProductList} from "./screens/Products/List";

到这一行:

const ScreensProductList = lazy(() => import('./screens/Products/List'));

但是 import('./screens/Products/List') 部分触发了 TypeScript 错误,说明:

But the import('./screens/Products/List') part triggers a TypeScript error, stating:

Type error: Type 'Promise<typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.
  Property 'default' is missing in type 'typeof import("/Users/johannesklauss/Documents/Development/ay-coding-challenge/src/screens/Products/List")' but required in type '{ default: ComponentType<any>; }'.

我不太确定我应该在这里做什么才能让它工作.

I am not quite sure what I am supposed to do here to get it to work.

推荐答案

You should do export default class {...} from the ./screens/Products/list> 而不是 export class ScreensProductList {...}.

You should do export default class {...} from the ./screens/Products/list instead of export class ScreensProductList {...}.

或者,您可以这样做:

const ScreensProductList = lazy(() =>
  import('./screens/Products/List')
    .then(({ ScreensProductList }) => ({ default: ScreensProductList })),
);

这篇关于在 TypeScript 中使用 React.lazy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆