reactjs - @apollo/client error-React Hook "useQuer

当我使用@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/

相关文章:

kubernetes - 使用 Persistent Volume Claim 时是否必须显式创建

r - 如何在保留 R 中的某些变量的同时将长整形为宽

r - 制作数据框每一列的向量并返回列表中的向量

reactjs - 如何触发事件 React 测试库

terraform - 如何定义 "azurerm_resource_group_template_

python - 如何划分字典值?

arrays - 使用 jq 将两个 JSON 数组合并到一个文件中

python - 无法用pip安装pycuda

swiftui - 编辑 : How we can alignment Image with Ima

postgresql - Ecto:如何用不同的随机数更新所有记录