繁体   English   中英

如何在同一个组件中使用自定义反应查询钩子两次?

[英]How to use custom react query hook twice in the same component?

我有一个自定义钩子,用于使用 useQuery 获取数据。 钩子工作正常,没有问题。

  const getData = async (url) => { 
     try{
          return await axios(url) 
         } catch(error){ 
           console.log(error.message)
           } 
         }

 export const useGetData = (url, onSuccess) => {
 return useQuery('getData', () => getData(url), {onSuccess})
}

但是,如果我在组件中调用此钩子两次,即使使用不同的 URL,它也只会从第一次调用中获取数据。 (忽略评论错字,这是故意的)

我的组件中的调用:

    const { data: commentss, isLoading: commentsIsLoading } = useGetData(`/comments/${params.id}`)
    const { data: forumPost, isLoading: forumPostIsLoading } = useGetData(`/forum_posts/${params.id}`)

在这种情况下,当我 console.log forumPost 时,它是评论数组而不是论坛帖子,即使我传递的是不同的端点。

我怎样才能使用这个钩子两次来获取不同的数据? 可能吗? 我知道我可以只调用并行查询,但如果可能的话,我想使用我的钩子。

由于useQuery基于queryKey缓存,因此在该名称中使用 URL

 const getData = async(url) => { try { return await axios(url) } catch (error) { console.log(error.message) } } export const useGetData = (url, onSuccess) => { return useQuery('getData' + url, () => getData(url), { onSuccess }) } //........ const { data: commentss, isLoading: commentsIsLoading } = useGetData(`/comments/${params.id}`) const { data: forumPost, isLoading: forumPostIsLoading } = useGetData(`/forum_posts/${params.id}`)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM