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

查看:47
本文介绍了Apollo 客户端是否在 React 中缓存嵌套对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进行以下查询:

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

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

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

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.

推荐答案

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

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 })
    },
  },
});

另见:

这篇关于Apollo 客户端是否在 React 中缓存嵌套对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆