【问题标题】:Does Apollo cache.readQuery return a copy?Apollo cache.readQuery 是否返回副本?
【发布时间】:2018-07-03 11:24:23
【问题描述】:

我正在浏览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 }
        });

【问题讨论】:

    标签: reactjs apollo apollo-client


    【解决方案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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-06
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2021-03-13
      相关资源
      最近更新 更多