【问题标题】:Pass ID from React to Apollo to find correct result?将 ID 从 React 传递给 Apollo 以找到正确的结果?
【发布时间】:2018-06-29 00:36:18
【问题描述】:

我将 React 与 Apollo(Apollo Client v2)一起使用。我有需要返回单个组的组查询。

此代码有效,但我已硬编码 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');
    },
}

【问题讨论】:

    标签: react-apollo apollo-client


    【解决方案1】:

    您需要做三件事:

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

    options 可以是一个函数,而不是一个对象,在这种情况下,它会将组件的 props 作为其第一个参数传递。然后,您可以使用这些道具来定义您的查询将使用的变量。您可以阅读更多关于在 Apollo 客户端 herehere 中使用变量的信息。

    【讨论】:

    • IM 收到一些错误:modules.js localhost:3000/graphql400(错误请求)和未处理(在 react-apollo:Apollo(GroupPage) 中)错误:网络错误:响应不成功:收到状态代码 400
    • 我在 root 和 id 的解析器中放置了一个 console.log,所以我知道正在传递什么。我得到未定义和一个空对象。
    • 我试图一步一步地工作。我使用的是 Graphiql 界面,所以我知道这不是 React 问题。从 Graphiql 传递参数的语法是什么? { group(_id:"dfd") { name } }
    • 对不起!只需要重建我的服务器并刷新 GraphiQL 页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2019-10-31
    • 2019-10-06
    • 2019-01-24
    • 2012-08-22
    • 2022-01-16
    • 2018-07-15
    相关资源
    最近更新 更多