这里写目录标题
使用场景:
在进行接口调用的时候,我们需要异步获取数据,在没有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
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,
参考
版权声明:本文为weixin_47664795原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。