React Query useQuery钩子引发错误→React -hooks/rules-of-hooks



我有一个示例组件如下。我试图使用React查询从我的端点(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)
}

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

一切顺利。

现在,每当我试图加载这个组件时,我都会得到以下错误

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)

但它是所有问题发生的点。

你能让我知道我该怎么做,我在这里想做什么吗?如果有一些例子的帮助,那将是很大的帮助。

感谢

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

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

https://reactjs.org/docs/hooks-rules.html解释

最新更新