假设我有一个在单个页面上具有这些功能的 React 应用程序: 新书, 作者 xyz 的书籍, 创建新书
现在假设我创作了一本作者 xyz 的新书。页面更新了两处,多了一本新书,多了一本作者xyz的书。
apollo-react 和 relay 在解决这个问题的方法上有何不同?他们如何解决这个问题?我见过的大多数例子只显示了基本的突变
最佳答案
以下是在 Apollo 中解决此问题的方法。
假设我们正在为这部分 UI 使用以下查询:
query AllBooks {
newBooks {
title
author { name }
}
author(id: "stubailo") {
id
books {
title
}
}
}
当然在现实中你可能有一些分页、变量等。但是对于这个例子我只使用一些简单的东西。
现在,让我们编写一个 mutation 来创建那本新书,它可能看起来像:
mutation CreateBook($book: BookInput!) {
createBook(book: $book) {
title
author { name }
}
}
现在,我们在 Apollo 中有两个主要选项来处理这个问题。
第一个选项是简单地重新获取整个查询:
client.mutate(CreateBookMutation, {
variables: { book: newBook },
refetchQueries: [ { query: AllBooksQuery } ],
})
这简单而有效,但如果由于某种原因查询结果的计算成本过高,则可能效率不高。
第二个选项是通过更新整个查询结果来合并结果。您可以使用 updateQueries , 但最近引入的最新方法是对带有 new imperative write API 的突变使用 update
回调:
client.mutate(CreateBookMutation, {
variables: { book: newBook },
update: (proxy, mutationResult) => {
// Get data we want to update, in the shape of the query
const data = proxy.readQuery({ query: AllBooksQuery });
// It's fine to mutate here since this is a copy of the data
data.newBooks.push(mutationResult.createBook);
data.author.books.push(mutationResult.createBook);
// Write the query back to the store with the new items
proxy.writeQuery({ query: AllBooksQuery, data });
},
})
如您所见,使用 GraphQL 并不比其他数据加载解决方案更容易保持 UI 更新。 API 不会为您提供太多有关新数据应去向的信息,因此您必须告诉 Apollo 如何处理它。
值得注意的是,这仅适用于添加和删除项目 - 更新现有项目会自动进行。
关于reactjs - relay 或 Apollo-react 如何解决涉及多重关系的突变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42881377/