我有一个 apollo 包装的组件,它应该为我的组件提供来自 github graphql v4 api 的响应数据。我打算使用应用程序另一部分的字符串(SEARCH_QUERY)在我的 gql 查询中使用,但 github 不断返回 undefined
。我正在关注官方 apollo 文档 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 返回未定义。
const searchRepos = gql`
query searchRepos($type: searchType!, $query: String!) {
search(type: REPOSITORY, query: $query, first: 100) {
edges {
node {
... on Repository {
nameWithOwner
owner {
login
}
}
}
}
}
}
`
最佳答案
您的查询出错,因为您定义了变量 $type
- 但您实际上并未在查询中使用它。您实际上不必在查询中发送任何变量——您可以在查询中定义一个或多个变量,然后永远不要在 graphql
HOC 中定义任何变量。这将是一个有效的请求,并且由服务器来处理 undefined variable 。但是,如果您在查询本身内部定义任何变量,则必须在该查询内部使用它,否则查询将被拒绝。
在开发过程中,您可能会发现将 data.error
记录到控制台很有帮助,可以更轻松地识别查询问题。当查询格式错误时,GraphQL 抛出的错误通常具有很强的描述性。
旁注:您可能不想为变量使用静态值。您可以根据传递给 HOC 所包装组件的 props 来计算变量(以及任何其他选项)。请参阅this section在文档中。
const options = ({someProp}) => ({
variables: { query: someProp, type: 'REPOSITORY' },
notifyOnNetworkStatusChange: true,
})
export default graphql(searchRepos, {options})(ReposList)
关于react-native - 如何在react-apollo graphql查询中正确使用动态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47000280/