当我试图使用TypeScript将一种反应组件导入另一种反应组件时发生React.lazy错误
templates/BugReport/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;templates/Footer/index.tsx
const BugReport = lazy(() =>
import(/* webpackChunkName: "bug-report" */ 'client/templates/BugReport'),
);虽然我在TypeScript中有默认导出,但Footer中有一个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文件,当我删除该文件时,错误就消失了,但是它需要在那里。
发布于 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。
https://stackoverflow.com/questions/68981171
复制相似问题