- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我阅读了 interacting with cached data 上的文档虽然我了解 cacheRedirects
的工作原理,但我有点困惑为什么需要它。这是我问另一个问题的部分原因:Does the Apollo client cache nested objects in React ?
We know that the data is most likely already in the client cache, but because it's requested with a different query, Apollo Client doesn't know that.
这是为什么?
为清楚起见,复制粘贴文档中的示例:
query ListView {
books {
id
title
abstract
}
}
query DetailView {
book(id: $id) {
id
title
abstract
}
}
最佳答案
Apollo 将接收到的数据缓存在 normalized 中方式。
如果您的ListView
返回如下数据:
{
"data": {
"books": [
{
"id": 1,
"title" "ABC",
"__typename": "Book"
},
{
"id": 2,
"title" "DEF",
"__typename": "Book"
}
]
}
}
每本书将根据其 id
和 __typename
存储在缓存中的键下 (Book:1
, Book :2
等)。然后,这个特定的缓存键列表与 books
根字段相关联。如果您再次请求 books
,Apollo 会发现缓存中已存在该查询,并将根据键列表重新创建结果。
如果 books
接受一些参数,则每组参数都被视为不同的缓存条目。 books(onSale: true)
可能会返回与 books(subject: "Computer Science")
不同的书籍集。每组缓存键都是单独存储的。如果您运行第一个查询,然后运行第二个查询,则第二个查询将是缓存未命中,并且仍会命中服务器。
类似地,您可以有一个接受一些参数并返回一本书的查询,例如 book(id: 1)
。但在所有这些示例中,Apollo 并不“理解”参数 id
和 onSale
是什么。这些参数与返回结果的关系是业务逻辑的一部分。 Apollo“知道”的就是给定这个查询和这组参数,您将获得这个特定的对象或对象数组。
作为一个人,我可以从命名中推断出像 book(id: 2)
这样的查询会返回一本 id 为 2
的书。但是像 Apollo 这样的库无法准确推断该信息 - 它如何猜测字段的正确类型或者它返回单个对象而不是对象数组?就此而言,它如何推断 id: 2
翻译为“Book where id = 2”?毕竟,实际参数可以有多种形式:book(identifier: 2)
、book(filter: { id: 2 })
等。
因此,我们使用cacheRedirects
来“教”Apollo如何查找可能已经在我们的缓存中的数据。这有效地复制了通常驻留在服务器上的一些业务逻辑,但有助于我们避免对服务器的额外调用。
关于graphql - 为什么我们需要 `cacheRedirects`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58844886/
我阅读了 interacting with cached data 上的文档虽然我了解 cacheRedirects 的工作原理,但我有点困惑为什么需要它。这是我问另一个问题的部分原因:Does th
我阅读了 interacting with cached data 上的文档虽然我了解 cacheRedirects 的工作原理,但我有点困惑为什么需要它。这是我问另一个问题的部分原因:Does th
我是一名优秀的程序员,十分优秀!