【问题标题】:How to use variables in a GraphQL query?如何在 GraphQL 查询中使用变量?
【发布时间】:2019-04-11 04:36:59
【问题描述】:

所以我必须做两个查询。 First 将返回一个包含多个对象的数组,我想获取第一个对象的 ID 以在我的第二个查询中使用它。

问题是我不能使用b_id: props.getBusiness.business[0]._id

知道如何使用它吗?

const GET_USER_BUSINESS = gql`
  query getUserBusiness {
    getUserBusiness {
        _id
    }
  }
`;

const GET_BUSINESS_JOBS = gql`
  query getBusinessJobs($b_id: ID!) {
    getBusinessJobs(b_id: $b_id ) {
        _id
        name
    }
  }
`;

export default compose(
    withApollo,
    graphql(GET_USER_BUSINESS,
        {
            name: "business"
        }),
    graphql(GET_BUSINESS_JOBS,
        {
            name: "jobs",
            options: (props) => (
                {
                    variables:
                    {
                        b_id: props.getUserBusiness.business[0].b_id
                    }
                }
            )
        })
)(ProposalContainer);

【问题讨论】:

  • 这个服务器端你也管吗?
  • @DavidMaze 不,这只是一个查询
  • getUserBusiness 听起来它会返回单个对象而不是数组......是吗?

标签: reactjs react-native graphql


【解决方案1】:

几件事。一,默认情况下,graphql HOC 将一个名为data 的道具传递给带有查询数据的包装组件。但是,因为您在 HOC 的配置中指定了 name,所以该道具实际上将被称为您传递给它的任何名称。换句话说,您可以通过这种方式访问​​_id:

props.business.getUserBusiness[0]._id

...如果 getUserBusiness 返回一个数组。否则:

props.business.getUserBusiness._id

其次,在查询完成之前,props.business 将是未定义的。我们可能不想发送GET_BUSINESS_JOBS 查询,直到我们有一个_id 可以使用。所以我们想将skip 函数传递给 HOC 的配置:

export default compose(
    withApollo,
    graphql(GET_USER_BUSINESS,
        {
            name: "business"
        }),
    graphql(GET_BUSINESS_JOBS,
        {
            name: "jobs",
            skip: (props) => !props.business || !props.business.getUserBusiness[0]
            options: (props) => (
                {
                    variables:
                    {
                        b_id: props.business.getUserBusiness[0]._id
                    }
                }
            )
        })
)(ProposalContainer)

【讨论】:

    猜你喜欢
    • 2020-01-22
    • 2022-01-21
    • 2021-01-06
    • 2019-05-17
    • 2023-03-12
    • 2019-12-03
    • 2018-03-02
    • 2019-02-15
    • 2019-12-23
    相关资源
    最近更新 更多