Javascript React Apollo - 进行多个查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43380704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:53:56  来源:igfitidea点击:

React Apollo - Make Multiple Queries

javascriptreactjsapolloreact-apollo

提问by user2465134

I have a queries file that looks like this:

我有一个如下所示的查询文件:

import {gql} from 'react-apollo';

const queries = {
  getApps: gql`
    {
      apps {
        id
        name
      }
    }
  `,
  getSubjects: gql`
    {
      subjects {
        id
        name
      }
    }
  `
};

export default queries;

I then import this file to my React component:

然后我将此文件导入到我的 React 组件中:

import React, {Component} from 'react'
import queries from './queries'

class Test extends Component {
...
}

export default graphql(queries.getSubjects)(graphql(queries.getApps)(Test));

This will only get data for one of the queries (getApps) and not both. If I do one at a time so that it looks like this:

这只会获取其中一个查询 (getApps) 的数据,而不是两者。如果我一次做一个,它看起来像这样:

export default graphql(queries.getSubjects)(Test);

then it works but I don't have my other query. Yes, I have tested both separately and they work. How do I get it so that both queries show up in my props.data?

然后它工作,但我没有我的其他查询。是的,我已经分别测试了它们并且它们有效。我如何获得它以便两个查询都显示在我的 props.data 中?

回答by Locco0_0

My preferred way is to use the composefunctionality of the apollo client (docu).

我的首选方法是使用composeapollo 客户端 ( docu) 的功能。

EDIT: If you have more than one query you should name them.

编辑:如果您有多个查询,您应该命名它们。

So in your case, it could look like this:

所以在你的情况下,它可能是这样的:

import React, {Component} from 'react'
import queries from './queries'
import { graphql, compose } from 'react-apollo';

class Test extends Component {
...

  render() {
    ...
    
    console.log(this.props.subjectsQuery, this.props.appsQuery); // should show both 
    
    ...
  }
}

export default compose(
   graphql(queries.getSubjects, {
      name: "subjectsQuery"
   }),
   graphql(queries.getApps, {
      name: "appsQuery"
   }),
)(Test);

回答by theVoogie

IMHO, one of the most neat solutions is described in the Apollo Client React implementation.
The basic idea is to wrap your queries into nested Query components. Using closure functions as component children makes it handy to delegate the results of one query down into another query and so on.

恕我直言,Apollo Client React implementation 中描述了最简洁的解决方案之一。
基本思想是将您的查询包装到嵌套的 Query 组件中。使用闭包函数作为子组件可以方便地将一个查询的结果委托给另一个查询等等。

 const QueryOne = gql`
  query One {
    one
  }
`;

const QueryTwo = gql`
  query Two {
    two
  }
`;

const NumbersWithData = () => (
  <Query query={QueryOne}>
    {({ loading: loadingOne, data: { one } }) => (
      <Query query={QueryTwo}>
        {({ loading: loadingTwo, data: { two }}) => {
          if (loadingOne || loadingTwo) return <span>loading...</span>
          return <h3>{one} is less than {two}</h3>
        }}
      </Query>
    )}
  </Query>
);

回答by Eesa

If you don't want to reuse any of those queries independently, why not make a single request by combining both queries in one i.e:

如果您不想独立重用这些查询中的任何一个,为什么不通过将两个查询组合在一起来发出单个请求,即:

const combinedQueries = gql`
{
  apps {
    id
    name
  }
  subjects {
    id
    name
  }
}
`

and then you can use it in your component

然后你可以在你的组件中使用它

import React, {Component} from 'react'
import combinedQueries from './combinedQueries'

class Test extends Component {
   ...
   render() {
     ...
     if(!this.props.combinedQueries.loading) {
       console.log(this.props.combinedQueries.apps);
       console.log(this.props.combinedQueries.subjects);
     }
     ...
   }
}

export default graphql(combinedQueries, {name: 'combinedQueries'})(Test);

回答by slorenzo

I'm using react-adoptto make this. It's really simple and keep our code clean.

我正在使用react-adopt来做到这一点。这真的很简单,并保持我们的代码干净。

Simple example:

简单的例子:

import { adopt } from 'react-adopt';

...
render() {
  const Composed = adopt({
    first: ({ render }) => <Query query={FIRST_QUERY}>{ render }</Query>,
    second: ({ render }) => <Query query={SECOND_QUERY}>{ render }</Query>
  });

  return (
    <Composed>
      ({ first, second }) => {
        console.log('first', first)
        console.log('second', second)

        // validations (loading, error)

        return (
          <div>Your JSX</div>
        )
      }
    </Composed>
  )
}
...

There are a lot of examples using

有很多例子使用

const Composed = adopt({
  first: <Query query={FIRST_QUERY} />,
  second: <Query query={SECOND_QUERY} />
});

Be careful with <Query>component, It needs a children, otherwise, it will have the following error:

小心<Query>组件,它需要一个孩子,否则会出现以下错误:

Warning: Failed prop type: The prop children is marked as required in Query, but its value is undefined.

To avoid the previous warning, I have found a possible solution:

为了避免之前的警告,我找到了一个可能的解决方案:

first: ({ render }) => <Query query={FIRST_QUERY}>{ render }</Query>

Hope it helps you!

希望对你有帮助!

回答by Freewalker

For Apollo 2.x: you can use react-adoptto compose the Queries and Mutations into a single level. (That lib will compose any components with render props, e.g. the React Context API.)

对于Apollo 2.x:您可以使用react-adopt将查询和突变组合成一个级别。(该库将使用渲染道具组合任何组件,例如 React Context API。)

https://github.com/pedronauck/react-adopt

https://github.com/pedronauck/react-adopt

回答by user3812429

Another way around this is to use the propsoption.

解决此问题的另一种方法是使用该props选项。

export default compose(
  graphql(QUERY_2, {
    props: ({ data }) => ({ ...data }),
  }),
  graphql(QUERY_1, {
    props: ({ data }) => ({ ...data, myCustomAttribute: data.foo }),
  }),
)(Component);

I've found that this approach is a bit nicer for my use case.

我发现这种方法更适合我的用例。

Here is a link to the docs: https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-config-props

这是文档的链接:https: //www.apollographql.com/docs/react/api/react-apollo.html#graphql-config-props

回答by sina

According to this Link, to use compose()you need to follow these steps:

根据此链接,要使用compose()您需要按照以下步骤操作:

1- install "recompose" package using npm i recompose

1-使用安装“重构”包 npm i recompose

2- import package using import { compose } from "recompose";

2-导入包使用 import { compose } from "recompose";

3- use it in the form of:

3-以以下形式使用它:

export default compose(
  graphql(Query1, { alias: "Query1" }),
  graphql(Query2, { alias: "Query2" })
)(Test);

documentation : https://www.apollographql.com/docs/react/api/react-apollo/

文档:https: //www.apollographql.com/docs/react/api/react-apollo/

回答by SHREY DUBEY

Since, compose has been removed from apollo, there's an alternative library called lodash. The method {flowRight} acts in the same way as compose. Just follow the steps:-

由于 compose 已从 apollo 中删除,因此有一个名为 lodash 的替代库。方法 {flowRight} 的作用与 compose 相同。只需按照以下步骤操作:-

  1. npm i -s lodash

  2. import {flowRight} from 'lodash'

  3. Exchange the usage of compose with flowRight, all the other code will work the same.

  1. npm i -s lodash

  2. import {flowRight} from 'lodash'

  3. 将 compose 与 flowRight 的用法交换,所有其他代码将工作相同。

回答by endorphin

  const { loading: cat_loading, cat_error, data: cat_data } = useQuery(categoriesAllQuery)
  const { loading: prod_loading, prod_error, data: prod_data } = useQuery(productsAllQuery)

  if (cat_loading || prod_loading) return <p>Loading ... </p>
  const { categoriesAll } = cat_data
  const { productsAll } = prod_data