【问题标题】:@apollo/client error-React Hook "useQuery" is called in function which is neither a React function component or a custom React Hook function@apollo/client 错误-React Hook "useQuery" 在既不是 React 函数组件也不是自定义 React Hook 函数的函数中调用
【发布时间】:2021-01-20 07:01:40
【问题描述】:

当我使用 @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 个不同的文件中。

【问题讨论】:

  • 如错误所述,您不能在组件之外使用挂钩。您的 graphqlService 不是组件
  • 我创建了一个功能组件,我在其中使用 UseQuery 方法并从 Class 组件调用该功能组件。我仍然得到相同的错误。我将上述方法更新为功能组件,例如:function graphqlService(params:any = {}){}
  • 看不到功能组件,我们帮不了你。
  • 我更新了上面的查询,请检查
  • 您的 graphqlService 不是一个组件。请阅读文档reactjs.org/docs/components-and-props.html

标签: reactjs graphql apollo apollo-client


【解决方案1】:

useQuery 钩子只能在 react 组件中调用(参见:https://www.apollographql.com/docs/react/data/queries/

【讨论】:

  • 我创建了一个功能组件,我在其中使用 UseQuery 方法并从 Class 组件调用该功能组件。我仍然得到相同的错误。我将上述方法更新为功能组件函数 graphqlService(params:any = {}){}
【解决方案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;

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2023-02-19
    • 2020-11-29
    • 1970-01-01
    • 2020-08-26
    • 2019-10-21
    • 2022-08-07
    • 2020-03-18
    相关资源
    最近更新 更多