Apollo 不会公开同时查询多个操作的钩子。但是,GraphQL 支持每个操作查询多个根字段。这一事实与别名字段的能力相结合,意味着您可以在单个请求中获取所有所需的数据。
在编写查询时通常应该远离字符串插值,但在这种情况下我们需要使用它。
const MyComponent = (options) => {
const query = gql`
query SomeNameForYourOperation (
${options.map((option, index) => `$opt${index}: SomeInputType!`).join('\n')}
){
${options.map((option, index) => `
alias${index}: someRootField(someArgument: $opt${index}) {
...SomeTypeFragment
}
`).join('')}
}
fragment SomeTypeFragment on SomeType {
someField
someOtherField
}
`
const variables = options.reduce((memo, option, index) => {
return { ...memo, [`opt${index}`]: option }
}, {})
const { data, loading, error } = useQuery(query, { variables })
if (data) {
// data.alias0
// data.alias1
// etc.
// You can also iterate through options again here and access the
// appropriate alias by the index
}
}
这看起来有点复杂,但实际上非常简单。我们通过迭代生成变量定义options
(我们最终得到像这样的变量$opt0
, $opt1
, ETC。)。然后,我们再次迭代选项以生成根的选择集。对于每个选项,我们将相同的字段添加到查询中,但我们为其别名(如alias0
, alias1
等),然后将不同的变量传递给该字段的参数。最后,我们利用片段来保持结果查询的大小易于管理。
我们还必须通过一个variables
反对useQuery
与我们生成的变量定义相匹配,所以我们reduce
the options
数组转换为具有适当命名属性的对象。
当然,您需要更改上面的示例以包含特定于您的查询的类型、字段和参数。最终结果是您拥有一组data
, loading
and error
变量。查询加载后,您可以使用适当的别名(alias0
, etc.).