Apollo cache.readQuery是否返回副本?



我正在浏览突变文档,想知道cache.readQuery是否返回副本?

例如:

const { todos } = cache.readQuery({ query: GET_TODOS });
// Should I copy it first or is it already copied?
// todos = Object.assign({}, todos)
todos.items.concat([addTodo])
cache.writeQuery({
query: GET_TODOS,
data: { todos: todos }
});
readQuery

返回副本

您现在可以通过读取然后更改然后再次读取查询来测试这一点,以查看结果是否已更改

const { todos } = cache.readQuery({ query: GET_TODOS });
todos[0].completed = null;
const data.todos = cache.readQuery({ query: GET_TODOS });
console.log(data.todos[0].completed) // true or false

源代码

如果我们看一下源代码,我们可以看到readQuery归结为这个函数graphqlAnywhere

const result = graphqlAnywhere(
readStoreResolver,
query,
rootIdValue,
context,
variables,
{
fragmentMatcher: fragmentMatcherFunction,
resultMapper,
},
);
return {
result,
complete: !context.hasMissingField,
};

每个 graphqlAnywhere 函数都以一个新对象开头,没有对缓存存储的直接引用,因此您无需担心在变异之前制作副本。

https://github.com/apollographql/apollo-client/blob/master/packages/graphql-anywhere/src/graphql.ts

https://github.com/apollographql/apollo-client/blob/91f5116ce830151e6bedf92e10550c607984e11c/packages/apollo-cache-inmemory/src/readFromStore.ts#L175

最新更新