reactjs - @apollo/client error-React Hook "useQuery"is called in function which is neither a React function component or a custom React Hook function

标签 reactjs graphql apollo apollo-client

当我使用@apollo/client 调用graphql api 时出现以下错误

React Hook“useQuery”在函数“graphqlService”中被调用,它既不是 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 个不同的文件中编写。

最佳答案

我在功能组件中遇到了同样的问题,这肯定是正确的。我通过使用大写字母作为组件名称来修复此错误消息。

official docs 中描述了为什么它需要大写字母

例子:

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;

关于reactjs - @apollo/client error-React Hook "useQuery"is called in function which is neither a React function component or a custom React Hook function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64208175/

相关文章:

javascript - 使用 Jest 测试 React/Redux 组件

linux - 在 linux 中创建 react-native 应用程序时出错

graphql - 不变违规 : Expecting a parsed GraphQL document

javascript - 为什么我无法使用 Apollo Link State 添加待办事项?

javascript - React( native )- 在第 3 方代码/组件中注入(inject)自定义组件而不是标准组件

javascript - 指向后端端点的链接在电子邮件文本中显示不正确

graphql - Prisma 生成 : Field configuration to merge has duplicate field names

error-handling - 如何使用 Apollo Server 2.0 GraphQL 将架构指令中的信息作为返回的数据包含在内?

react-native - Apollo GraphQL Client 不适用于 React Native 中的发布版本

javascript - React-router 弄乱了请求 url