Tanstack Query(reactQuery)

使用场景:

在进行接口调用的时候,我们需要异步获取数据,在没有useQuery时,需要频繁使用hooks中的usestate和useEffect,代码量很大很复杂。

使用useQuery能够大大减轻我们获取异步接口数据的代码负担。

💡 Query results by default are structurally shared to detect if
data has actually changed
and if not, the data reference remains
unchanged
to better help with value stabilization with regards to
useMemo and useCallback.

import { useQuery } from 'react-query'
const { data, refetch, isLoading } = useQuery(
    ['replies', item.id, pagination.page, pagination.pageSize],
    async () => {
      return await api.comments.listThread(
        item.id,
        (pagination.page - 1) * pagination.pageSize,
        pagination.pageSize,
      )
    },
    { 
      enabled: expanded, //tell a query when it is ready to run
      retry: 10, // Will retry failed requests 10 times before displaying an error
      retryDelay: 1000, // Will always wait 1000ms to retry, regardless of how many retries
      keepPreviousData : true
    }, 
  )

使用useQuery

参数:

https://react-query-v3.tanstack.com/reference/useQuery

  • A unique key for the query (必需)
  • A function that returns a promise that:(必需)
    • Resolves the data, or
    • Throws an error
  • enabled,是否触发
  • retry,false不重试,num尝试num次,true无限制重试,(failureCount, error) => {}自定义逻辑
  • retryDelay 重试延迟
  • keepPreviousData,获取多页面数据时不丢弃已获取到的内容
  • cacheTime
  • initialData
  • initialDataUpdatedAt
  • isDataEqual
  • meta
  • notifyOnChangeProps
  • notifyOnChangePropsExclusions
  • onError
  • onSettled
  • onSuccess
  • placeholderData
  • queryKeyHashFn
  • refetchInterval
  • refetchIntervalInBackground
  • refetchOnMount
  • refetchOnReconnect
  • refetchOnWindowFocus
  • retryOnMount
  • select
  • staleTime
  • structuralSharing
  • suspense
  • useErrorBoundary,

参考

https://zhuanlan.zhihu.com/p/539387280

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值