我正在使用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
作为查询的变量,但是,上面的代码显示以下错误:
“消息”:必需类型为“ ID!\”的变量\“ $ id \”不是 提供。”
答案 0 :(得分:0)
此属性允许您配置传递到组件的prop的名称。默认情况下,如果您传递给graphql()
的GraphQL文档是一个查询,则您的prop将被命名为data
。如果您通过了突变,那么您的道具将被命名为mutate
。当您尝试对同一组件使用多个查询或变异时,这些默认名称会适当地冲突。为避免冲突,您可以使用config.name
为每个query
或mutation
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);