如何在查询 onClick 后更新查询 props.data

how to update a query props.data after a query onClick

我正在使用 Apollo 执行 2 个查询,
第一个查询由 Apollo 自动执行,
第二个查询在单击按钮时执行,结果如下查询应该更新第一个查询的一部分(就像 updateQueries 对突变所做的那样)。

这是我试过的代码:

import React from 'react';
import {graphql, withApollo} from 'react-apollo';
import gql from 'graphql-tag';

class MaPage extends React.Component {

  loadAllResults = ()=> {
        return this.props.client.query({
            query: query2,
            variables: {userId: 'user_id_1'}
            //I want to update the results of query1 by the results of query2
        });
    }

  render() {
        if (this.props.data.loading) {
            return (
                <div>Loading... </div>
            );
        }
        else {
            return (
                <div>
                    {this.props.data.user.allResults.map((result)=> {
                        return (<span >{result.score} | </span>)
                    })
                    }
                    <button onClick={this.loadAllResults}>load all results</button>
                </div>
            );
        }
    }
}

const query1 = gql`
    query GetInfos ($userId:ID!)){
        user(id:$userId){
            id
            name
            allResults(first:2){
                id
                score
            }
            #get other attributes
        }
    }
`;
const query2 = gql`
    query getAllResults ($userId:ID!){
        allResults(userId:$userId){
            id
            score
        }
    }
`;

export default  withApollo(
    graphql(query1,
        {
            options: (ownProps) => {
                return {
                    variables: {userId: 'user_id_1'}
                };
            }
        }
    )
    (MaPage));

您可以在 query1 中添加一个 reducer with type==='APOLLO_QUERY_RESULT'operationName==='getAllResults'

示例:

graphql(query1,
  {
    options: (ownProps) => {
     return {
       variables: {userId: 'user_id_1'},
       reducer: (previousResult, action) => {
                 if (action.type === 'APOLLO_QUERY_RESULT' && action.operationName === 'getAllResults'){
                    return update(previousResult, {
                       user: { ... }
                    })
                 }
                return previousResult;
              }
            };
        }
    }
)

更多信息在 http://dev.apollodata.com/react/cache-updates.html#resultReducers