我正在浏览mutation doc,想知道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 }
});
答案 0 :(得分:1)
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