【问题标题】:React Query useQuery hooks raising an error → react-hooks/rules-of-hooksReact Query useQuery hooks 引发错误 → react-hooks/rules-of-hooks
【发布时间】:2021-02-27 13:23:27
【问题描述】:

我有一个示例组件如下。我正在尝试使用 React Query 从我的端点(Graphql)获取数据。我有一个自定义钩子,我也在下面列出。

const App =(props)=>{  
if (me && me.token) {
    let headers = {
        Authorization: me.token,
    }
    const { loading, error, data } = useGQLQuery('getUploads', GetUploadedFiles, headers)
    let tableData = []
    if (data && data.uploads) {
      tableData = data.uploads
    }
  } else {
    message.info("You need to be logged in to manage your assets!")
    return;
  }
}

自定义挂钩 →

export const useGQLQuery = (key, query, variables,headers={}, config = {}) => {
  let gqlClient = new GraphQLClient(endpoint)
  const fetchData = async () => gqlClient.request(query, variables, headers)
  return useQuery(key, fetchData, config)
}

我想在 header 中传递当前用户的令牌信息。

到目前为止一切顺利。

现在,每当我尝试加载此组件时,都会收到以下错误

React Hook "useGQLQuery" is called conditionally. 
React Hooks must be called in the exact same order in every component render. 
Did you accidentally call a React Hook after an early return?  react-hooks/rules-of-hooks

我需要传递当前用户的令牌,这就是我这样做的原因

if (me && me.token) {
    let headers = {
        Authorization: me.token,
    }
    const { loading, error, data } = useGQLQuery('getUploads', GetUploadedFiles, headers)

但这是所有问题发生的地方。

你能告诉我我该怎么做吗,我想在这里做什么。 对一些示例的任何帮助都会有很大帮助。

谢谢

【问题讨论】:

    标签: reactjs react-query


    【解决方案1】:

    你在 if 条件中调用了一个钩子。 React 不允许这样做。它需要在每次重新渲染时都进行一致的钩子调用以跟踪更改。 您需要修改您的 useGQLQuery 挂钩,以便它在内部处理您的逻辑条件,例如 me && me.token

    下面是为什么你不能从 if 条件调用钩子的解释:

    https://reactjs.org/docs/hooks-rules.html#explanation

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2020-10-30
      • 2019-10-06
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      相关资源
      最近更新 更多