首页 > 解决方案 > 迁移后如何更新存储

问题描述

我有一个评论列表,其中每个评论都是Message组件。

一条消息有一个“编辑”按钮,点击这个按钮,它的文本被替换为表单,它没有连接到 ApolloClient。

Message组件也只是用于显示数据,它没有连接到 ApolloClient。

代码如下:

import React from 'react';
import gql from 'graphql-tag';
import { graphql, compose } from 'react-apollo';
import { number } from 'prop-types';
import withCurrentUser from '!/lib/hoc/withCurrentUser';
import Message from '!/components/messages/Message';


class CompanyComments extends React.Component {
  static propTypes = {
    companyId: number.isRequired
  };

  updateComment = (content, contentHTML, id) => {
    const {doEditCommentMutation, companyId} = this.props;

    return doEditCommentMutation({
      variables: {
        id: id,
        content: content
      }
    });
  }


  render(){
    const { data: {loading, comments}, companyId } = this.props;

    return(
      <div>
        <ul>
          {
            !loading &&
            comments &&
            comments.map((comment, i)=>(
              <Message
                key={i}
                index={i}
                id={comment.id}
                content={comment.content}
                user={comment.user}
                onReply={this.handleReply}
                handleUpdate={(content, contentHTML)=>(
                  this.updateComment(content, contentHTML, comment.id)
                )} />
            ))
          }
        </ul>
      </div>
    );
  }
}

const getCommentsQuery = gql`query
  getComments(
    $commentableId: Int,
    $commentable: String
  ) {
    comments(
      commentableId: $commentableId,
      commentable: $commentable,
      order: "createdAt ASC"
    ) {
      id
      content
      user {
        id
        nickname
      }
      createdAt
    }
  }
`;

const editCommentMutation = gql`mutation
  editCommentMutation(
    $id: Int!,
    $content: String!
  ) {
    editComment(
      id: $id,
      content: $content
    ) {
      id
      content
      createdAt
      user {
        id
        nickname
      }
    }
  }
`;

export default compose(
  graphql(getCommentsQuery, {
    options: ({companyId}) => ({
      variables: {
        commentableId: companyId,
        commentable: 'company'
      },
      pollInterval: 5000
    })
  }),
  graphql(editCommentMutation, {name: 'doEditCommentMutation'})
)(CompanyComments);

唯一连接到 ApolloClient 的组件是带有上述代码的组件。

有趣的行为开始了,当editComment执行突变并且通过getComments查询接收到的组件列表神奇地更新时。

如何?我没有使用乐观的反应或refetch.

是不是使用 ApolloClient 存储的新行为,而不是 Redux,自动找出获取数据的变化?

标签: react-apolloapollo-client

解决方案


我看到pollInterval: 5000一个

graphql(
  getCommentsQuery, 
  { 
    options : { ... }  // << here
  }
)

pollInterval强制重复获取查询。在您的示例中,每 5 秒。在这里了解更多

由于 Apollo 缓存存储了规范化的数据,因此任何具有相同数据的项目__typenameid将在存储中更新,并且它的 UI 表示会为正在侦听任何返回它们的查询的组件自动更新。有关自动缓存更新的更多信息。


推荐阅读