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

React中页面刷新持久化GraphQL数据,仅查询变更时重新请求

实现GraphQL数据持久化与按需请求方案

针对你的需求,我们可以通过缓存持久化和优化Apollo查询策略来实现页面刷新保留数据、仅查询变更时发起新请求的效果,具体方案如下:

1. 配置持久化缓存

默认的InMemoryCache是内存级缓存,页面刷新后会清空。我们需要借助apollo3-cache-persist将缓存数据持久化到本地存储(如localStorage),实现刷新后数据保留。

步骤1:安装依赖

npm install apollo3-cache-persist
# 或使用yarn
yarn add apollo3-cache-persist

步骤2:修改index.js配置持久化缓存

import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";
import { persistCache, LocalStorageWrapper } from "apollo3-cache-persist";
import ReactDOM from "react-dom/client";

// 创建缓存实例
const cache = new InMemoryCache();

// 初始化持久化缓存(异步操作,需等待完成后渲染组件)
async function initApp() {
  try {
    await persistCache({
      cache,
      // 使用localStorage存储缓存数据
      storage: new LocalStorageWrapper(window.localStorage),
    });
  } catch (err) {
    console.error("缓存持久化初始化失败:", err);
  }

  const client = new ApolloClient({
    uri: process.env.BASE_URL,
    cache,
  });

  const root = ReactDOM.createRoot(document.getElementById("root"));
  root.render(
    <React.StrictMode>
      <ApolloProvider client={client}>
        <RouterProvider router={router} />
      </ApolloProvider>
    </React.StrictMode>
  );
}

initApp();

2. 优化组件查询策略

通过配置useQuery的fetchPolicy,确保优先使用缓存数据,仅当查询变量变更或缓存无对应数据时发起新请求。

修改组件代码

import { useQuery } from "@apollo/client";
import { useSearchParams } from "react-router-dom";

const Component = () => {
  const [searchParams] = useSearchParams();
  // 从URL参数中获取查询变量(确保变量与查询内容绑定)
  const queryVariables = {
    keyword: searchParams.get("keyword") || "",
    // 其他查询参数...
  };

  const { loading, error, data } = useQuery(queryGql, {
    variables: queryVariables,
    // 优先使用缓存,缓存存在时不发起请求
    fetchPolicy: "cache-first",
    // 后续组件更新时仍保持缓存优先策略
    nextFetchPolicy: "cache-first",
  });

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }
  const results = data?.data || [];

  return (
    <div>
      {results.map((result) => (
        <Card name={result.name} key={result.id} />
      ))}
    </div>
  );
};

export default Component;

方案说明

  • 持久化缓存:通过apollo3-cache-persist将Apollo的缓存数据同步到localStorage,页面刷新后会自动从本地存储恢复缓存,避免数据丢失。
  • 缓存优先策略:fetchPolicy: "cache-first"让Apollo先检查缓存中是否存在匹配当前查询和变量的数据,存在则直接使用;只有缓存无对应数据时才发起API请求。
  • 按需请求触发:当queryVariables(如URL搜索参数)变更时,Apollo会生成新的缓存键,若缓存中无对应新变量的数据,则自动发起新的API请求,完全符合“仅查询内容变更时请求”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:43:27