我正在尝试使用Apollo查询GraphQl API。我正在用打字稿在React中做到这一点,但我无法让Query组件停止抛出错误。 我是整个组合的新手,所以我可能在做某些明显错误的事情。有什么想法吗?
这是错误:
Type '{ children: (string | (({ loading, error, data }: QueryResult<any, OperationVariables>) => any))[]; query: any; }' is not assignable to type 'Pick<Readonly<QueryProps<any, OperationVariables>> & Readonly<{ children?: ReactNode; }>, "children" | "displayName" | "skip" | "onCompleted" | "onError" | "ssr" | "variables" | ... 6 more ... | "partialRefetch">'.
Types of property 'children' are incompatible.
Type '(string | (({ loading, error, data }: QueryResult<any, OperationVariables>) => any))[]' is not assignable to type '((result: QueryResult<any, OperationVariables>) => ReactNode) | (((result: QueryResult<any, OperationVariables>) => ReactNode) & string) | (((result: QueryResult<any, OperationVariables>) => ReactNode) & number) | ... 4 more ... | (((result: QueryResult<...>) => ReactNode) & ReactPortal)'.
Type '(string | (({ loading, error, data }: QueryResult<any, OperationVariables>) => any))[]' is not assignable to type '((result: QueryResult<any, OperationVariables>) => ReactNode) & ReactNodeArray
这是我的代码:
import React from 'react';
import gql from "graphql-tag";
import { Query } from "react-apollo";
export interface LoginProps {
data: object; item: string; query: object; loading: string; error: string;
};
const getLogin =
gql`
{
viewer {
login
}
}
`;
export class Test extends React.Component<LoginProps, {}> {
<Query query={getLogin}>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
return data.viewer.map( item => {
<div key={item.login}>
<p>{item.login}</p>
</div>
});
}};
</Query>
};
export default Test;
答案 0 :(得分:0)
首先,由于您没有在组件上使用状态,因此建议您使用
React.FunctionComponent
而不是React.Component
。
关于您的问题:您必须在组件的渲染功能内使用jsx
组件,例如:
export class Test extends React.Component<LoginProps, {}> {
// HERE: use the render method
render() {
return (
<Query query={getLogin}>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
return data.viewer.map(item => {
<div key={item.login}>
<p>{item.login}</p>
</div>;
});
}}
;
</Query>
);
}
}
希望有帮助。
答案 1 :(得分:0)
显然无关紧要,但是对于那些来这里寻找答案的人来说,Query
内部的解构就像这样:
<Query query={getLogin}>
{(result: QueryResult) => {
const { loading, error, data } = result;
// ...rest here
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
return data.viewer.map( item => {
<div key={item.login}>
<p>{item.login}</p>
</div>
});
}};
</Query>