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

时间:2017-03-30 17:02:40

标签: facebook-graph-api graphql react-apollo apollo-client scaphold

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

  • 组件1查询用户列表
  • 组件2订阅该活动 创建新用户

我无法找到根据组件2订阅结果更新组件1结果的方法。
COMPONENT1:

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>
                    );
    }
}

2 个答案:

答案 0 :(得分:3)

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

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

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

看起来像这样:

&#13;
&#13;
...

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)
&#13;
&#13;
&#13;

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