简体   繁体   English

如何在 React + Apollo GraphQL 中查询先前查询的结果?

[英]How to query with result of prior query in React + Apollo GraphQL?

In one of my components, I'm immediately querying my backend.在我的一个组件中,我立即查询我的后端。 Afterwards, I want to query my backend again with the data from my first query, so the variables of my second query are from the first.之后,我想用第一个查询中的数据再次查询我的后端,所以我的第二个查询的变量来自第一个。

I've tried useLazyQuery but either it does not work, or I'm incorrectly placing it.我试过useLazyQuery但要么它不起作用,要么我放错了位置。 I've tried using skip in the useQuery hook but it doesn't seem to work, because I'm the condition I'm testing against to skip, is also the variable I'm using for the query itself, and I'm checking whether or not it is defined.我已经尝试在useQuery挂钩中使用skip但它似乎不起作用,因为我是我测试要跳过的条件,也是我用于查询本身的变量,我正在检查它是否被定义。

I'd rather not use compose as I'm mainly working with hooks in my React Component and I'm not sure of how to structure them and fit them in with my code.我宁愿不使用compose ,因为我主要在我的 React 组件中使用钩子,我不确定如何构造它们并将它们与我的代码相匹配。

I'm also using both query results separately.我也分别使用这两个查询结果。 My backend is structured like a tree so I'm using both one node and its child.我的后端结构像一棵树,所以我同时使用一个节点及其子节点。

I wouldn't use useLazyQuery for this if I can avoid it, because it's a different query lifecycle than the more common useQuery .如果可以避免,我不会为此使用useLazyQuery ,因为它与更常见的useQuery是不同的查询生命周期。 It could work, but let's try with useQuery .它可以工作,但让我们尝试使用useQuery

You want the first query, query1 , to be executed unconditionnaly.您希望第一个查询query1无条件执行。 Easy.简单的。

You want the second query, query2 , to be executed only when query1 has returned a result.您希望第二个查询query2仅在query1返回结果时执行。 Then it's a matter of using skip on query2 based on what query1 returned.然后是根据query1返回的内容在query2上使用skip的问题。 In the simplest form:以最简单的形式:

const { loading: loading1, error: error1, data: data1 } = useQuery('...query1...');
const { loading: loading2, error: error2, data: data2 } = useQuery('...query2...', {
  variables: {
    myVariable: data1 && data1.path.to.data,
  }
  skip: !data1, // This is simpler that checking error1 and loading1.
});

Additionally, you might want to prevent the second query from executing if the first query did not return enough results.此外,如果第一个查询没有返回足够的结果,您可能希望阻止执行第二个查询。 Depending on your exact schema and query, it could be something like this:根据您的确切架构和查询,它可能是这样的:

  skip: !data1 || !data1.searchForIDs || data1.searchForIDs.length === 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM