You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 02:40:18