我有一个名为HandleQuery
的React组件,它处理Apollo GraphQL查询的结果:
import React, { ReactNode } from 'react';
import { CenteredMessage } from './centered-message';
export interface HandleQueryProps {
loading: boolean,
error?: Error,
children: ReactNode
}
export const HandleQuery = ({ loading, error, children }: HandleQueryProps) => {
if (loading) {
return <CenteredMessage>Loading...</CenteredMessage>;
}
if (error) {
return <CenteredMessage>{error.message}</CenteredMessage>;
}
return children;
};
当该组件用于另一个组件时,它不会编译:
import React from 'react';
import { useQuery } from 'react-apollo-hooks';
import gql from 'graphql-tag';
import { HandleQuery } from '..';
import { MutationType } from '../../graphql-types';
import { AuthorsPanel } from './authors-panel';
import { GET_AUTHORS } from './authors-queries';
import { AuthorMutated } from './__generated__/AuthorMutated';
export class AuthorsContainer extends React.Component {
render() {
const { loading, error, data } = useQuery(GET_AUTHORS);
return (
<!-- THIS LINE PRODUCES A COMPILER ERROR -->
<HandleQuery loading={loading} error={error}>
<AuthorsPanel data={data} />
</HandleQuery>
);
}
}
使用上述HandleQuery
会产生以下错误:
类型错误:JSX元素类型"{}|null | undefined"不是JSX元素的构造函数.
这意味着什么?我怎样才能摆脱它?
Update
将AuthorsContainer转换为函数组件并不能消除错误:
export const AuthorsContainer = () => {
const { loading, error, data } = useQuery(GET_AUTHORS);
return (
<HandleQuery loading={loading} error={error}>
<AuthorsPanel data={data} />
</HandleQuery>
);
};
Update 2
import React from 'react';
import { CenteredMessage } from './centered-message';
export interface HandleQueryProps {
loading: boolean;
error?: Error;
}
export const HandleQuery: React.FC<HandleQueryProps> = ({
loading,
error,
children
}) => {
if (loading) {
return <CenteredMessage>Loading...</CenteredMessage>;
}
if (error) {
return <CenteredMessage>{error.message}</CenteredMessage>;
}
return children;
};
现在容器组件上的错误消失了,但HandleQuery
组件上出现了一个新的编译器错误:
Type error: Type '({ loading, error, children }: PropsWithChildren<HandleQueryProps>) => {} | null | undefined' is not assignable to type 'FunctionComponent<HandleQueryProps>'.
Type '{} | null | undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'.
Type 'undefined' is not assignable to type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | null'. TS2322