![](/img/trans.png)
[英]ReactJS/Javascript/Graphql/React-apollo: passing query variables
[英]How Can I correctly use dynamic variables in react-apollo graphql query?
我有一个用阿波罗包装的组件,应该为我的组件提供来自github graphql v4 api的响应数据。 我打算在我的gql查询中使用应用程序另一部分中的字符串(SEARCH_QUERY),但是github始终返回undefined
。 我正在关注官方的阿波罗文档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
}
}
}
}
}
}
`
您的查询出错了,因为您定义了变量$type
,但是实际上并没有在查询中使用它。 您不必在查询中实际发送任何变量-您可以在查询中定义一个或多个变量,然后再在graphql
HOC内部不定义任何graphql
。 这将是一个有效的请求,并且将由服务器处理未定义的变量。 但是,如果您在查询内部定义了任何变量,则必须在该查询中使用该变量,否则查询将被拒绝。
在开发过程中,您可能会发现将data.error
记录到控制台会更有用,以便更轻松地确定查询问题。 当查询格式错误时,由GraphQL引发的错误通常是描述性的。
注意:您可能不想为变量使用静态值。 您可以从传递到HOC包装的组件的道具中计算变量(以及其他任何选项)。 请参阅文档中的此部分 。
const options = ({someProp}) => ({
variables: { query: someProp, type: 'REPOSITORY' },
notifyOnNetworkStatusChange: true,
})
export default graphql(searchRepos, {options})(ReposList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.