首页 > 解决方案 > React 组件显示为 2 个 ajax 调用的总和

问题描述

我正在使用 react , Apollo 客户端 , hooks

我想进行 2 个单独的 ajax 调用,一旦取回两个调用的结果,我必须使用从两个调用中检索到的值构建一个组件。

对于这种用例,是否有任何众所周知的模式可以遵循。

不幸的是,无法将 2 个 graphql 查询合并为 1 个。

标签: javascriptreactjsreact-hooksapollo-client

解决方案


这取决于您如何使用 apollo 客户端。基本上说你可以Promise.all这样使用

const [resultOne, resultTwo] = await Promise.all([
  client.query(query1),
  client.query(query2),
])
// then do something with this results

语法可能不正确,但我希望你明白。

如果您使用钩子,您可以编写查询以包含两个查询,就像这样

const combinedQuery = gql`
  query CombinedQuery($params1: Params1!, $params2: Params2) {
     queryOne(params1: $params1) {
       field1
       field2
     }
     queryTwo(params2: $params2) {
       field1
       field2
     }

  }
`

然后像这样使用它

const { data, loading, error } = useQuery(combinedQuery, { variables: {...} })

希望它会有所帮助。


推荐阅读