首页 > 解决方案 > 如何使用 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,则连接效果很好

标签: reactjsgraphqlapollo

解决方案


这可以在 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,
     }
  }
`

我希望它有帮助


推荐阅读