如何让React Query的fetchQuery发起新GET请求而非使用缓存?
强制React Query的fetchQuery发起全新请求的方法
React Query的fetchQuery默认优先读取缓存,要绕过缓存发起新请求,可通过以下几种方式实现:
1. 配置force: true参数
给fetchQuery添加force配置项,设置为true时会强制忽略现有缓存,发起全新GET请求。可以给函数加个参数控制是否强制刷新:
export const getVegetables = async (forceRefresh = false) => await queryClient.fetchQuery( ['getVegetables'], async () => { try { const { data } = await request.get('/vegetables'); return data; } catch (error) { throw new Error('Failed to fetch vegetables'); } }, { force: forceRefresh } );
需要刷新时调用:
getVegetables(true);
2. 设置数据立即过时并自动刷新
通过staleTime: 0让缓存数据立即变为"过时"状态,再配合refetchOnMount: true,每次调用函数都会重新请求最新数据:
export const getVegetables = async () => await queryClient.fetchQuery( ['getVegetables'], async () => { try { const { data } = await request.get('/vegetables'); return data; } catch (error) { throw new Error('Failed to fetch vegetables'); } }, { staleTime: 0, refetchOnMount: true } );
3. 先清除缓存再请求
如果需要彻底清除对应缓存后再获取数据,可以先调用removeQueries清除缓存,再执行原函数:
// 强制刷新的调用逻辑 await queryClient.removeQueries(['getVegetables']); await getVegetables();
内容的提问来源于stack exchange,提问作者Onyx
相关产品推荐
相关产品推荐

