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

RTK Query轮询时如何从Redux Store获取动态参数?

解决方案

核心结论

RTK Query的query函数是纯函数,无法直接访问Redux Store,但可以用queryFn替代query,通过getState方法获取Store状态,完美解决你的问题。

具体实现

将原API定义中的query替换为queryFn,在每次轮询请求时直接从Store读取最新的lastFetch,同时利用onQueryStarted钩子在请求成功后更新lastFetch:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { RootState } from './store'; // 导入你的RootState类型
import { updateLastFetch } from './dashboardSlice'; // 导入你的action

export const dashboardApi = createApi({
  reducerPath: 'dashboardApi',
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  endpoints: (builder) => ({
    getDashboardData: builder.query({
      // 使用queryFn替代query,可获取getState方法
      queryFn: async (args: { id: string }, { getState }) => {
        // 从Store中读取当前最新的lastFetch
        const state = getState() as RootState;
        const lastFetch = state.dashboard.lastFetch[args.id] || "1899-12-31T00:00:00.000Z";
        const endTime = new Date().toJSON();

        // 发起请求
        const response = await fetch(`/dashboard/${args.id}/data?start=${lastFetch}&end=${endTime}`);
        const data = await response.json();

        return { data };
      },
      // 请求成功后更新Store中的lastFetch
      onQueryStarted: async (args, { dispatch, queryFulfilled }) => {
        try {
          await queryFulfilled;
          const endTime = new Date().toJSON();
          dispatch(updateLastFetch({ lastFetch: endTime, id: args.id }));
        } catch (err) {
          // 可选:处理请求失败的情况
        }
      },
      // 开启每60秒轮询
      refetchInterval: 60000,
    }),
  }),
});

// 导出hooks
export const { useGetDashboardDataQuery } = dashboardApi;

为什么这个方案有效

  1. 无需将lastFetch作为useQuery的参数传入,避免了lastFetch更新时触发额外的请求。
  2. 每次轮询触发时,queryFn都会主动从Store读取最新的lastFetch,确保请求参数是最新值。
  3. 利用RTK Query自带的refetchInterval管理轮询,无需手动维护定时器。

其他可选方案(不推荐)

如果坚持使用query而非queryFn,可以用useLazyQuery手动控制轮询:

  • 用setInterval每隔60秒执行一次refetch。
  • 每次refetch前从Store读取最新的lastFetch作为参数传入。
  • 需要手动清理定时器,不如RTK Query自带的轮询机制简洁可靠。

内容的提问来源于stack exchange,提问作者HarryW

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:35:16