react-apollo:如何处理 update 和 updateQuery 中的不变性?

react-apollo: How to deal with immutability in update and updateQuery?

我在我的 React 应用程序中使用 react-apollo。现在需要分页以获取更多数据。独立于分页,如何更新 updateQueryupdate 中的状态?将深度嵌套的数据结构视为不可变使其变得冗长,但我不想向其添加帮助程序库。

fetchMore({
  variables: {
    cursor: cursor,
  },
  updateQuery: (previousResult, { fetchMoreResult }) => {
    return {
      ...previousResult,
      author: {
        ...previousResult.author,
        articles: {
          ...previousResult.author.articles,
          ...fetchMoreResult.author.articles,
          edges: [
            ...previousResult.author.articles.edges,
            ...fetchMoreResult.author.articles.edges,
          ],
        }
      }
    }
  },

改变 previousResult 是否可以,或者这是否违背了 Apollo 的理念?

const { pageInfo, edges } = fetchMoreResult.author.articles;
previousResult.author.articles.edges.concat(edges);
previousResult.author.articles.pageInfo = pageInfo;
return previousResult;

或者有其他更新状态的方法吗?

From the docs:

Note that the function must not alter the prev object (because prev is compared with the new object returned to see what changes the function made and hence what prop updates are needed).

我会硬着头皮按照文档的建议使用 immutability-helper。除此之外,您可以先复制对象 (Object.assign({}, fetchMoreResult)),然后您可以对副本执行任何操作。