将 ID 从 React 传递给 Apollo 以找到正确的结果?

Pass ID from React to Apollo to find correct result?

我正在使用 React 和 Apollo (Apollo Client v2)。我有需要 return 单个组的组查询。

此代码有效,但我已硬编码 HARD-CODED-ID。我怎样才能将 ID 作为字符串从 React 组件传递?

在我的 React 组件中:

const groupQuery = gql`
    query Group {
        group {
            _id
            name
        }
    }
`;

export default graphql(groupQuery, {
    props: ({ data }) => ({ ...data }),
})(GroupPage);

我的解析器:

Query: {
    groups() {
        return Groups.find().fetch();
    },
    group() {
        return Groups.findOne('HARD-CODED-ID');
    },
}

您需要做三件事:

1.) 如果您还没有修改服务器上的架构,以便您的查询接受 id 作为输入,例如:

type Query {
  #other queries
  group(id: ID!): Group
}

2.) 修改您的解析器,使其处理传入的 ID。假设您使用 graphql-tools:

group(root, { id }) {
  return Groups.findOne(id); // did you mean something like findOne({id}) ?
},

3.) 修改您的客户端代码。通常,您会将 id 作为传递给组件的道具,然后将其用作请求中的变量。

const groupQuery = gql`
    query Group($id: ID!) {
        group(id: $id) {
            _id
            name
        }
    }
`;

// assuming that the component prop is called groupId
export default graphql(groupQuery, {
    options: ({ groupId }) => ({
      variables: { id: groupId },
    }),
})(GroupPage);

选项可以是函数,而不是对象,在这种情况下,它将组件的道具作为第一个参数传递。然后,您可以使用这些道具来定义您的查询将使用的变量。您可以阅读有关在 Apollo 客户端 here and here.

中使用变量的更多信息