【问题标题】:How to include variables in the React Apollo query and execute it?如何在 React Apollo 查询中包含变量并执行它?
【发布时间】:2020-02-19 05:35:41
【问题描述】:

我正在使用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】:

    此属性允许您配置传递给组件的道具的名称。默认情况下,如果您传递给 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;
    }
    

    而你要使用的变量的key不在查询语句中,显示错误信息。

    使用选项变量

    export default graphql(gql`
      query ($width: Int!, $height: Int!) {
        ...
      }
    `, {
      options: (props) => ({
        variables: {
          width: props.size,
          height: props.size,
        },
      }),
    })(MyComponent);
    

    【讨论】:

      猜你喜欢
      • 2017-07-11
      • 2019-08-28
      • 1970-01-01
      • 2019-03-09
      • 2020-11-29
      • 2018-09-25
      • 2019-01-26
      • 1970-01-01
      • 2020-05-08
      相关资源
      最近更新 更多