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

如何在RTK Query中手动添加localStorage缓存作为接口初始数据?

解决方案

RTK Query 提供了 api.util.initializeQueryData 方法,专门用于创建或初始化缓存条目,正好解决你无法用 updateQueryData 添加新缓存的问题。

修改你的代码如下:

function App() {
  const dispatch = useDispatch()
  useEffect(() => {
    try {
      const json = localStorage.getItem('config')
      const config = json ? JSON.parse(json) : undefined
      if (config) {
        // 用 initializeQueryData 初始化缓存条目
        dispatch(
          api.util.initializeQueryData('getConfig', undefined, () => config)
        )
      }
    } catch(error) {
      console.error(error)
    }
  }, [dispatch, api.util.initializeQueryData])
  return <div />
}

关键说明:

  • initializeQueryData 的参数和 updateQueryData 完全一致:第一个是查询名称(对应你定义的 getConfig 接口),第二个是查询参数(你的接口无参数就传 undefined),第三个可以直接传数据,也可以传返回数据的函数。
  • 这个方法会直接在缓存中创建对应的条目,后续调用 useGetConfigQuery 时,RTK Query 会优先使用这个缓存数据,再根据你设置的 staleTime 等规则决定是否发起新请求。
  • 记得把 api.util.initializeQueryData 加入 useEffect 的依赖数组,避免闭包问题或不必要的重复执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:54:17