如何解决@ apollo / client error-React Hook“ useQuery”在既不是React函数组件也不是自定义React Hook函数的函数中调用
使用@ apollo / client进行graphql api调用时出现以下错误
在函数“ graphqlService”中调用“反应挂钩”“ useQuery”,该函数既不是React函数组件也不是自定义的React Hook函数react-hooks / rules-of-hooks
索引文件:
import { ApolloClient,InMemoryCache,ApolloProvider } from '@apollo/client';
const client = new ApolloClient({
uri: "http://localhost:3008",cache: new InMemoryCache()
});
ReactDOM.render(
<ApolloProvider client={client}>
<App/>
</ApolloProvider>,document.getElementById('root')
);
功能组件文件:
import React from 'react';
import {
useQuery,gql
} from "@apollo/client";
import Schema from '../models/schema';
function graphqlService( params : any = {} ) {
const query = Schema.getPanelData;
const { data } = useQuery(query,{variables: params});
if (data) return data;
}
export default graphqlService;
类组件文件:
this.data = graphqlService(params);
我不认为这是软件包的问题,我在POC项目中的同一软件包中使用了相同的软件包。那里工作正常。唯一的不同是我将所有代码都写在同一文件中,在这里我写了2个不同的文件。
解决方法
只能在react组件中调用useQuery挂钩(cf:https://www.apollographql.com/docs/react/data/queries/)
,我在功能组件中存在相同的问题,可以肯定是正确的。我通过使用大写字母作为组件名称来修复此错误消息。
中说明了为什么需要大写字母示例:
import React from "react";
import Query from "./Query";
import { useQuery } from "@apollo/client";
const ComponentName = () => {
const { loading,error,data } = useQuery(Query);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
...
);
};
export default ComponentName;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。