如何根据其他组件的订阅结果更新组件的查询结果?

how to update the results of a component's query based on the results of an other component's subscription?

我在同一个页面上有 2 个 React 组件,

我想不出一种方法来根据组件 2 的订阅结果更新组件 1 的结果。
组件 1:

class Comp1 extends React.Component {

    render() {
        return (
            <div>
            {this.props.data.loading? <span>loading…</span>
        : <span> //show the list of users </span>       }
        </div>
                    );
    }
}

export default graphql(queryAllUsers)(Comp1) ;

组件 2 :

class Comp2 extends React.Component {
   constructor(props) {
     super(props);
        this.state = {
        newUserCreated: false
            }
   }
 subscribeToNewUser() {
    this.subscription = this.props.data.subscribeToMore({
        document: subscribeToNewUsersQuery,
        variables: {//        },
    });
    }
    render() {
        return (
            <div>
            {this.state.newUserCreated}
        </div>
                    );
    }
}

我想最简单的方法是在第一个组件中也使用查询并通过 subscribeToMore 函数添加订阅。

可能看起来像这样:

...

subscribeToNewUser() {
    this.subscription = this.props.queryAllUsers.subscribeToMore({
      document: subscribeToNewUsersQuery,
      variables: { /* your variables */ },
      updateQuery: (previousResult, { subscriptionData }) => {
        const changedItem = subscriptionData.data.<subscriptionName>;
        if (changedItem !== undefined && changedItem !== null) {
          return // update previous result
        }
        return previousResult;
      },
    });
  }


  ...

  export default graphql(queryAllUsers, {
    name: "queryAllUsers"
  })
  ...
  (Comp1)

其中有 updateQuery 功能,将在订阅事件中调用。当结果数据良好时,您可以更新商店,例如将新值推送到用户数组

解决方案是在查询第一个组件时使用 reducer 函数:

class Comp1 extends React.Component {
  render() { ... }
}

export default graphql(queryAllUsers, {
      options: (ownProps) => {
        return ({
            variables: { ...
            },
            reducer: (previousResult, action) => {
              if (action.type === "APOLLO_SUBSCRIPTION_RESULT" && action.operationName === "subscribeToNewUsersQuery") {
                //update the previousResult
                return previousResultWithNewData;
              } else return previousResult;
            })
        }
      })(Comp1);