首页 文章

如何在react-apollo graphql查询中正确使用动态变量?

提问于
浏览
2

我有一个apollo包装的组件,它应该为我的组件提供来自github graphql v4 api的响应数据 . 我打算使用应用程序另一部分的字符串(SEARCH_QUERY)在我的gql查询中使用,但github继续返回 undefined . 我正在关注正式的apollo docs http://dev.apollodata.com/react/queries.html#graphql-options . 我看不出我做错了什么 .

import React, { Component } from 'react';
import { Text, FlatList  } from 'react-native';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { SEARCH_QUERY } from './Home' // this is a string like "react"

// The data prop, which is provided by the wrapper below contains,
// a `loading` key while the query is in flight and posts when ready
const ReposList = ({ data: { loading, search }}) => <Text>SearchResults</Text>

// this doesnt work because I cant properly inject 'SEARCH_QUERY' string
const searchRepos = gql`
  query searchRepos($type: searchType!, $query: String!) {
    search(type: REPOSITORY, query: $query, first: 100) {
      edges {
        node {
          ... on Repository {
            nameWithOwner
            owner {
              login
            }
          }
        }
      }
    }
  }
`
// The `graphql` wrapper executes a GraphQL query and makes the results
// available on the `data` prop of the wrapped component (ReposList here)
export default graphql(searchRepos, {
  options: { variables: { query: SEARCH_QUERY }, notifyOnNetworkStatusChange: true }
  }
)(ReposList);

没有变量的此查询运行良好,并按预期返回搜索结果 . 直截了当吧?

const searchRepos = gql`{
search(type: REPOSITORY, query: "react", first: 100) {
   edges {
     node {
       ... on Repository {
         nameWithOwner
         owner {
           login
         }
       }
     }
   }
 }

}

当使用它时,github返回undefined .

const searchRepos = gql`
  query searchRepos($type: searchType!, $query: String!) {
    search(type: REPOSITORY, query: $query, first: 100) {
      edges {
        node {
          ... on Repository {
            nameWithOwner
            owner {
              login
            }
          }
        }
      }
    }
  }
`

1 回答

  • 3

    您的查询错误,因为您已定义变量 $type - 但您不必实际使用您的查询发送任何变量 - 您可以在查询中定义一个或多个,然后永远不要在 graphql HOC中定义任何变量 . 这将是一个有效的请求,由服务器来处理未定义的变量 . 但是,如果在查询本身内部定义任何变量,则必须在该查询中使用它,否则将拒绝查询 .

    在开发过程中,您可能会发现将 data.error 记录到控制台以更轻松地识别查询问题会很有帮助 . 当查询格式错误时,GraphQL抛出的错误通常非常具有描述性 .

    旁注:您可能不希望为变量使用静态值 . 您可以从传递给HOC包装的组件的props中计算变量(以及任何其他选项) . 请参阅文档中的this section .

    const options = ({someProp}) => ({
      variables: { query: someProp, type: 'REPOSITORY' },
       notifyOnNetworkStatusChange: true,
    })
    export default graphql(searchRepos, {options})(ReposList)
    

相关问题