在进行接口调用的时候,我们需要异步获取数据,在没有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
false
不重试,num
尝试num次,true
无限制重试,(failureCount, error) => {}
自定义逻辑