如何在React Apollo查询中包括变量并执行它?

问题描述 投票:0回答:1

我正在使用compose在一个组件中执行多个查询。我希望能够对查询使用变量。

1)如何在查询中包含变量?

2)如何执行查询?

以下为组件:

import React from 'react'
import {
    View,
} from 'react-native'
import { graphql, withApollo } from 'react-apollo'
import { compose } from "recompose";

import { GET_ITEM, GET_REVIEWS } from '../graphql/query'

const PostingDetail = props => {
    const itemId = props.navigation.getParam('itemId', null)

    console.log("props", props.itemQuery)

    return (
        <View>
        </View>
    )
}


export default compose(
    withApollo,
    graphql(GET_ITEM, { 
        name: 'itemQuery',
        options: ({ itemId }) => ({
            variables: {
                id: itemId
            }
        })
    }), 
    graphql(GET_REVIEWS, { name: 'reviewsQuery'}), 
)(PostingDetail)

我希望能够使用itemId作为查询的变量,但是,以上代码显示以下错误:

“ message”:不是必需类型\“ ID!\”的变量\“ $ id \”提供。”

reactjs react-native graphql react-apollo
1个回答
0
投票

此属性允许您配置传递到组件的prop的名称。默认情况下,如果您传递给graphql()的GraphQL文档是查询,则您的prop将被命名为data。如果您通过了突变,那么您的道具将被命名为mutate。当您尝试对同一组件使用多个查询或变异时,这些默认名称会适当地冲突。为避免冲突,您可以使用config.name为每个querymutation HOC中的道具提供一个新名称。

示例

export default compose(
  graphql(gql`mutation (...) { ... }`, { name: 'createTodo' }),
  graphql(gql`mutation (...) { ... }`, { name: 'updateTodo' }),
  graphql(gql`mutation (...) { ... }`, { name: 'deleteTodo' }),
)(MyComponent);

function MyComponent(props) {
  // Instead of the default prop name, `mutate`,
  // we have three different prop names.
  console.log(props.createTodo);
  console.log(props.updateTodo);
  console.log(props.deleteTodo);

  return null;
}

并且您要使用的变量的键不在查询语句中,显示错误消息。

使用选项的变量

export default graphql(gql`
  query ($width: Int!, $height: Int!) {
    ...
  }
`, {
  options: (props) => ({
    variables: {
      width: props.size,
      height: props.size,
    },
  }),
})(MyComponent);
© www.soinside.com 2019 - 2024. All rights reserved.