在React中,Apollo客户端会缓存嵌套对象吗?[英] Does the Apollo client cache nested objects in React?

本文是小编为大家收集整理的关于在React中,Apollo客户端会缓存嵌套对象吗?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

采取以下疑问:

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

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

有时,运行第二个查询让我获得一个缓存的bar.其他时候,它没有,但我不确定这是否是因为查询是运行倍数的,或者因为这是Apollo客户端在反应中的默认行为.

推荐答案

no,它没有(截至2019年11月,至少).要在运行Foo查询时将bar对象放入缓存中,需要创建如此:

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

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

还请参阅:

本文地址:https://www.itbaoku.cn/post/1938112.html

问题描述

Take the following queries:

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

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

Sometimes, running the 2nd query gets me a cached version of bar. Other times, it doesn't, but I'm not sure if this is because the query is run multiples times or because that's the default behaviour of the Apollo client in React.

推荐答案

No, it doesn't (as of Nov 2019, at least). To put the bar object in the cache when running the Foo query, you need to create the in-memory cache like this:

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

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

Also see: