1

updateuseMutation 的钩子中,Apollo 的文档建议使用writeFragment来获取对新添加对象的内部引用。我觉得这很奇怪,因为该对象已经存在于缓存中。所以我测试了它,readFragment果然,它运行良好。在这个用例中是否有使用writeFragmentover的偏好readFragment

示例 1:

https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates

const [addTodo] = useMutation(ADD_TODO, {
    update(cache, { data: { addTodo } }) {
      cache.modify({
        fields: {
          todos(existingTodos = []) {
            const newTodoRef = cache.writeFragment({
              data: addTodo,
              fragment: gql`
                fragment NewTodo on Todo {
                  id
                  type
                }
              `
            });
            return [...existingTodos, newTodoRef];
          }
        }
      });

该页面的摘录:

在 cache.writeFragment 的帮助下,我们获得了对添加的 todo 的内部引用,然后将该引用存储在 ROOT_QUERY.todos 数组中。

示例 2:

https://www.apollographql.com/docs/react/caching/cache-interaction/#example-updating-the-cache-after-a-mutation

const [addComment] = useMutation(ADD_COMMENT, {
  update(cache, { data: { addComment } }) {
    cache.modify({
      fields: {
        comments(existingCommentRefs = [], { readField }) {
          const newCommentRef = cache.writeFragment({
            data: addComment,
            fragment: gql`
              fragment NewComment on Comment {
                id
                text
              }
            `
          });
          return [...existingCommentRefs, newCommentRef];
        }
      }
    });
  }
});

该页面的摘录:

该评论已通过 useMutation 添加到缓存中。因此,cache.writeFragment 返回对现有对象的引用。

我还在 Apollo Client 的讨论板 ( https://github.com/apollographql/apollo-client/discussions/7515 ) 上发布了这个问题,但没有得到回复。

4

1 回答 1

2

此处解释了从缓存中获取项目时使用writeFragmentover的好处readFragment(摘自https://www.apollographql.com/docs/react/caching/cache-interaction/#example-updating-the-cache-after-a-突变):

如果您使用缓存能够识别的 options.data 对象调用 writeFragment,则基于其 __typename 和主键字段,您可以避免将 options.id 传递给 writeFragment。

无论您是显式提供 options.id 还是让 writeFragment 使用 options.data 来计算,writeFragment 都会返回对已识别对象的引用。

这种行为使 writeFragment 成为获取对缓存中现有对象的引用的好工具,在为 useMutation 编写更新函数时可以派上用场

这是违反直觉的,因为writeFragment顾名思义,它是用于写入缓存而不是从中读取,但它似乎是推荐的最佳实践。

于 2020-12-29T16:53:23.367 回答