reactjs - 类型'typeof import(“...”)'中缺少属性'default',但类型'{默认值:ComponentType; }'
问题描述
当我尝试使用将一个 React 组件导入另一个组件时出现 TypeScript 错误React.lazy
模板/错误报告/index.tsx
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;
模板/页脚/index.tsx
const BugReport = lazy(() =>
import(/* webpackChunkName: "bug-report" */ 'client/templates/BugReport'),
);
Footer
尽管我有默认导出,但我收到 TypeScript 错误BugReport
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 文件夹中也有文件,当我删除该文件时错误消失了,但它需要在那里
解决方案
我知道我回答迟了,但也许其他人将来会遇到同样的问题,就像我刚刚做的一样并且自己想通了,但在前往此页面并没有找到任何答案之前。
是什么导致了您的问题
您正在使用 Typescript,但没有将您的函数输入为 React 组件。
React.lazy() 期望一个 React 组件作为输入。
由于您的函数返回 null 并且未键入,因此 React.Lazy 无法知道它是 React 组件。
解决方案
要解决此问题,您可以:
选项 1 -将您的返回值从 null 更改为类似的片段return <></>;
,或
选项 2 -从功能组件切换到类组件。由于 Clas 组件必须有一个render()
方法,因此即使带有return null;
or也会被检测为 React 组件
选项 3 - 切换到箭头函数并向其添加类型,例如 React.FC 或 React.FunctionComponent。-const BugReport: FC = () => null;
对于未来进入这里的任何人。在我输入的时候,为了让 React.lazy() 工作,你应该遵循上面提到的三个选项之一,并且正如@Hayk 所说,你的组件必须有一个export default YourComponent
.
推荐阅读
- docker - 如何将索引从自托管的 Elasticsearch 转换/迁移到 ES docker 容器?
- javascript - P5.js 类未识别
- excel - Excel - 按正则表达式或类似方法拆分字符串
- amazon-web-services - 在存储桶中显示 AWS S3 cli 上传后出现问题
- apache-spark - 使用 Spark / Scala 从数据框中的单个记录创建多个记录?
- google-app-engine - 用户/服务帐户、范围、AppEngine 和 GSuite(工作表 v4 api)
- html - 如何将背景图像设置为仅屏幕的左半部分
- python - 从 Django 视图中的特定论坛类别获取线程
- c - 无法使用 Visual Studio 的 Empty WDM 驱动程序模板中的 NDIS 相关功能
- jenkins - 如何处理詹金斯 http -> https 重定向?