将React.lazy与TypeScript配合使用

0ve6wy6x  于 2023-01-27  发布在  TypeScript
关注(0)|答案(7)|浏览(158)

我正在尝试使用React.lazy在我的TypeScriptReact应用程序中进行代码拆分。
我所做的就是改变这句话:

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

到这一行:

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

但是import('./screens/Products/List')部分触发了一个TypeScript错误,指出:

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>; }'.

我不太清楚我应该在这里做些什么才能让它发挥作用。

avwztpqn

avwztpqn1#

您应该从./screens/Products/list而不是export class ScreensProductList {...}执行export default class {...}
或者,您可以执行以下操作:

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

gxwragnw2#

一个选项是在“./screens/Products/List”中添加默认导出,如下所示

export default ScreensProductList;

第二种方法是将导入代码更改为

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

或者,如果您不介意使用外部库,您可以:

import { lazily } from 'react-lazily';
const { ScreensProductList } = lazily(() => import('./screens/Products/List'));
c3frrgcw

c3frrgcw3#

另一种解决办法是:

1.使用延迟导入

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

2.设置导出类型

反作用钩子

import { FunctionComponent /*, FC */ } from 'react';

const List = () => (
  return </>;
);

export default List as FunctionComponent; // as FC;

React类组件

import { Component, Fragment, ComponentType } from 'react';

class List extends Component {
  render() {
    return <Fragment />;
  }
}

export default List as ComponentType;
oalqel3c

oalqel3c4#

这是正确的语法。它也适用于Webstorm IDE(此处显示的其他语法仍然显示警告)

const ScreensProductList = React.lazy(() => import("./screens/Products/List").then(({default : ScreensProductList}) => ({default: ScreensProductList})));
ct2axkht

ct2axkht5#

const LazyCart = React.lazy(async () => ({ default: (await import('../Components/market/LazyCart')).LazyCart }))
xqnpmsa8

xqnpmsa86#

您可以创建一个索引.ts文件,您可以在其中导出所有组件,如下所示:

export {default as YourComponentName} from "./YourComponentName";

之后,您可以使用React.lazy:

React.lazy(() => import("../components/folder-name-where-the-index-file-is-created").then(({YourComponentName}) => ({default: YourComponentName})))
zour9fqk

zour9fqk7#

只是为了扩展这个答案,这也适用于dynamic导入。

const Navbar = dynamic(() => import('../components/Navbar'), {
  ssr: false,
});

其中,Navbar是默认导出元件。

const Navbar = () => ()

export default Navbar

相关问题