React-Apollo-在变异的更新功能中不清楚使用readQuery / writeQuery

时间:2018-11-23 14:56:11

标签: reactjs react-apollo apollo-client

我对于在传递给react-apollo中的变异函数的更新函数的上下文中readQuery和writeQuery的工作方式一无所知。 似乎readQuery返回了对缓存的引用,对返回的对象进行更改会直接触发具有相关更改的组件之间的重新渲染,那为什么我需要调用writeQuery?

直接从传递给mutate的更新函数的文档(https://www.apollographql.com/docs/react/features/optimistic-ui.html)的示例:

update: (proxy, { data: { submitComment } }) => {
          // Read the data from our cache for this query.
          const data = proxy.readQuery({ query: CommentAppQuery });
          // Add our comment from the mutation to the end.
          data.comments.push(submitComment);
          // Write our data back to the cache.
          proxy.writeQuery({ query: CommentAppQuery, data });
        }

现在我是否注释掉最后一行:

update: (proxy, { data: { submitComment } }) => {
          // Read the data from our cache for this query.
          const data = proxy.readQuery({ query: CommentAppQuery });
          // Add our comment from the mutation to the end.
          data.comments.push(submitComment);
          // Write our data back to the cache.
          // proxy.writeQuery({ query: CommentAppQuery, data });
        }

一旦proxy.readQuery返回的数据发生突变,我的组件和UI就会发生变化。调用proxy.writeQuery有什么额外的好处? 最初,我认为必须使用proxy.writeQuery来通知React的更改并触发对我的组件的重新渲染,但是显然不是这种情况。

0 个答案:

没有答案