javascript - React 组件显示为 2 个 ajax 调用的总和
问题描述
我正在使用 react , Apollo 客户端 , hooks
我想进行 2 个单独的 ajax 调用,一旦取回两个调用的结果,我必须使用从两个调用中检索到的值构建一个组件。
对于这种用例,是否有任何众所周知的模式可以遵循。
不幸的是,无法将 2 个 graphql 查询合并为 1 个。
解决方案
这取决于您如何使用 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: {...} })
希望它会有所帮助。
推荐阅读
- google-sheets - 使用随机样本填充新的 Google 表格工作表,其中至少包含 X 个给定属性的样本
- kotlin - RxJava Maybe:有什么巧妙的方法来处理 Empty case?
- css - 如何使弹性框中的旋转元素固定在页面右侧?
- android - 根据子项动态调整布局大小
- .net - 无法转换 COM 对象 (EXCEL)
- react-native - React Native STUCK 启动打包器
- asp.net-core-2.0 - 如何在管道早期对 JWT 不记名令牌进行自定义验证
- arrays - 结构问题中的Golang数组
- javascript - 如何在文本输入完成时起飞
- apache-beam - 在 beamSQL 中实现 ROW_NUMBER()