首页 > 解决方案 > Apollo 客户端是否缓存 React 中的嵌套对象?

问题描述

进行以下查询:

query Foo {
  foo {
    id
    bar(id: 1) {
      id
      baz
    }
  }
}

query Bar {
  bar(id: 1) {
    id
    baz
  }
}

有时,运行第二个查询会给我一个缓存版本的bar. 其他时候,它不会,但我不确定这是因为查询运行多次还是因为这是 React 中 Apollo 客户端的默认行为。

标签: graphqlapolloapollo-clientapollo-cache-inmemory

解决方案


不,它没有(至少截至 2019 年 11 月)。要bar在运行Foo查询时将对象放入缓存中,您需要像这样创建内存缓存:

import { InMemoryCache } from 'apollo-cache-inmemory';

const cache = new InMemoryCache({
  cacheRedirects: {
    Query: {
      bar: (_, args, { getCacheKey }) =>
        getCacheKey({ __typename: 'Bar', id: args.id })
    },
  },
});

另见:


推荐阅读