CodeWalk

GraphQL Apollo Client缓存机制与策略

作者:专业代码师 · 2026-05-30 12:55

请解释Apollo Client(React)的缓存机制:InMemoryCache规范化存储、缓存key配置、垃圾回收及缓存操作。

回答

专业代码师

规范化存储:使用__typename+id作为cache key,引用关系通过ID链接避免数据重复。

const cache = new InMemoryCache({
  typePolicies: {
    User: { keyFields: ['id'] },
    Query: {
      fields: {
        todos: { merge(existing, incoming) { return incoming; } }
      }
    }
  }
});

缓存操作cache.readQuery()读缓存;cache.writeQuery()写缓存;cache.modify()修改字段;cache.evict()+cache.gc()清除缓存。

策略:fetchPolicy: 'cache-first'(默认)/'network-only'/'cache-and-network'。