reactjs - 如何使用 React 加入状态中的多个 Apollo 查询?
问题描述
我是 React 和 Apollo 应用于 MongoDB 的新手,我有以下问题:
我有一张表(ID - ID_A - ID_B),我对此进行了查询并返回了一个数组。之后,我必须在另一个表中为数组中的每个组件询问与 ID_A 的匹配。
所以我做了:
{this.props.firstGet.map((data, index) => {
const id = data.ID_A;
return (
<Query key={this.props.firstGet.id} query={QUERY} variables={{ id }}>
{({ loading, error, data }) => {
if (loading) return 'Loading...';
if (error) return `Error ${error.message}`;
this.test = this.test.concat({...data.getStartup, ...this.state.applicants[index]});
return(this.test.length === this.props.getApplicants.length ?
<LastTable startups={this.test}></LastTable>
: '')
}
}
</Query>
);
哪一个是我的问题的最佳实践?我需要第一个数组,其中每个对象的组合都带有第二个表的答案。例如,有没有办法在不使用 LastTable 的情况下直接进入主状态?
我如何解决它: 1)在 MainTable MongoDB 模式中添加:
ID_A: {
type: mongoose.Schema.ObjectId,
ref: 'Table1'
}
2)在graphQl shcema中:ID_A:Table1Object
3)在解析器中添加 .populate('ID_A')
我现在将尝试插入一个新的,也许我有问题,但如果在 MainTable ID_A 字段中使用 ID,则连接效果很好
解决方案
这可以在 graphql 服务器端处理。您只需要请求从服务器端解析并返回这些依赖字段。
举个例子——
1.使用字段和子字段创建模式, 例如
type Person {
id: ID!
cars: [Car]
}
type Car {
id:ID!
ownerId: Int!
model: String
}
2.您需要在服务器端编写嵌套解析器
人物解析器:
import Query from './query';
import Mutation from './mutation';
export default {
Query, //<----- person query resolver
Mutation, //<----- person mutation resolver if any
Person: { . //<----- Nested fields resolver on Person
cars: (parent, args, { dataSources }) => {
const { id: ownerId } = parent;
// return from db cars owned by person
return dataSources.carAPI.getCarsByOwnerId(ownerId);
},
},
};
我在这里使用数据源,但您可以直接从数据库中使用解析。
3.客户端查询
export const GET_PERSON_WITH_CARS = gql`
query getPersonWithCars($id: ID!) {
person(id: $id) {
id
cars {
id,
ownerId,
model,
}
}
`
我希望它有帮助
推荐阅读
- python - Beautifulsoup 在解析前转义无效的 xml 字符
- elasticsearch - 将 Kibana(弹性搜索)嵌入 WordPress?
- .htaccess - 通过删除参数问号重定向某些子文件夹
- php - 向轮播添加 Alt 标签
- sql - 数据透视表中的标识符无效
- flask - 增加不活动计时器 Flask 应用程序
- android - 无法解决:support-media-compat 打开文件
- python - 使用包含句点字符的字符串的Python字典索引?
- c - . C 编程 - 通过套接字发送信号?
- php - 如何获得数量的总和并发送到另一个表(Laravel)