当前位置: 首页 > 工具软件 > react-query > 使用案例 >

Tanstack Query(reactQuery)

惠翰藻
2023-12-01

使用场景:

在进行接口调用的时候,我们需要异步获取数据,在没有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

 类似资料:

相关阅读

相关文章

相关问答