首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >属性'default‘在’type in import(“.”)类型中缺失但在类型“{ default: ComponentType<any>;}”中需要

属性'default‘在’type in import(“.”)类型中缺失但在类型“{ default: ComponentType<any>;}”中需要
EN

Stack Overflow用户
提问于 2021-08-30 08:40:48
回答 1查看 1.3K关注 0票数 1

当我试图使用TypeScript将一种反应组件导入另一种反应组件时发生React.lazy错误

templates/BugReport/index.tsx

代码语言:javascript
复制
import { useEffect, useContext } from 'react';
import BugReportStatic from '@tamm/ui-lib-v2-bug-report';
import baseUrl from 'client/utils/baseUrl';
import { StoreContext } from 'client/services/context';

function BugReport() {
  const store = useContext(StoreContext);
  useEffect(() => {
    BugReportStatic.init({
      bugReportIntegrationApi: `${baseUrl}/pub/feedback/bugReport`,
      store,
      isStore: !!store,
    });
    return () => {
      BugReportStatic.destroy();
    };
  }, []);
  return null;
}

export default BugReport;

templates/Footer/index.tsx

代码语言:javascript
复制
const BugReport = lazy(() =>
  import(/* webpackChunkName: "bug-report" */ 'client/templates/BugReport'),
);

虽然我在TypeScript中有默认导出,但Footer中有一个BugReport错误

代码语言:javascript
复制
Type 'Promise<typeof import("/Users/hayksimonyan/Desktop/JTUpdates/dcd/src/client/templates/BugReport/index")>' is not assignable to type 'Promise<{ default: ComponentType<any>; }>'.
  Property 'default' is missing in type 'typeof import("/Users/hayksimonyan/Desktop/JTUpdates/dcd/src/client/templates/BugReport/index")' but required in type '{ default: ComponentType<any>; }'.ts(2322)
index.d.ts(789, 34): 'default' is declared here.
index.d.ts(789, 18): The expected type comes from the return type of this signature.
module "/Users/hayksimonyan/Desktop/JTUpdates/dcd/src/client/templates/BugReport/index"

这里有一个注意事项,我在index.ts文件夹中也有BugReport文件,当我删除该文件时,错误就消失了,但是它需要在那里。

EN

回答 1

Stack Overflow用户

发布于 2022-02-21 00:59:56

我知道我的回答迟到了,但也许其他人将来也会遇到同样的问题,就像我刚才自己做的那样,但在进入这一页之前却找不到任何答案。

是什么导致了你的问题

您使用的是类型记录,而不是将您的函数键入为React组件。

React.lazy()期望一个React组件作为输入。

由于您的函数返回null且未键入,React.Lazy无法知道它是一个React组件。

解决方案

要解决这个问题,您可以:

选项1-将返回从null更改为像return <></>;这样的片段,或者

选项2-从函数组件切换到类组件。由于Clas组件必须具有render()方法,因此即使使用return null;

选项3-切换到箭头函数并向其添加类型,如React.FC或React.FunctionComponent。- const BugReport: FC = () => null;

为了将来任何一个来到这里的人。在我输入的时候,要使React.lazy()工作,您应该遵循上面提到的三个选项之一,正如@Hayk所说,您的组件必须有一个export default YourComponent

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68981171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档