【问题标题】:Query data with GraphQL in React with data from a previous query在 React 中使用 GraphQL 查询数据以及来自先前查询的数据
【发布时间】:2018-02-16 08:54:57
【问题描述】:

所以通常我对使用 apollo react 和 GraphQL 查询或变异数据没有任何问题。但有一件事我只是不明白:假设我有一个查询得到一个任意实体的 Id,如下所示:

const Query = graphql(
  baseNodeQuery([
    'entityId',
    'entityLabel'
  ], 'employment_reference_preset'), {
    options: {
      variables: {
        filter: {
          type: "employment_reference_preset"
        },
        limit: 1000,
        offset: 0
      }
    }
  })
(ExampleComponent);

baseNodeQuery 是一个自定义函数,它接受一些参数来使用 gql() 准备查询。但无论如何,在我的 ExampleComponent 中,我可以使用这样的数据:

const EmploymentReferencePresetEntity = ({data: {loading, error, nodeQuery}}) => {
  if (loading) {
    return <p>Loading...</p>;
  }
  if (error) {
    return <p>{error.message}</p>;
  }

  return (
    <div>
      //do something with the data form nodeQuery
    </div>
  )
};

但是,当我想使用从上一个查询中获得的 Id 进行第二次查询并将该 Id 用作过滤器时呢?当我像以前一样在我的 ExampleComponent 中返回另一个 graphql 查询时,我收到一个错误,即我没有返回有效的反应组件。那我该怎么做呢?

提前致谢!

【问题讨论】:

    标签: reactjs graphql react-apollo


    【解决方案1】:

    过去我能够做到这一点的方法是将“子”查询分离到它自己的组件中。

    假设您有一个向您展示所有行星的太阳系组件。所以你有一个查询来返回没有细节的行星,另一个查询叫做 planetDetails 或其他东西。你创建你的 SolarSystem 组件并用你的父查询包装它,然后其中的每个行星将加载另一个组件并将planetID 作为道具传递给它。在该组件上,您包装了 planetDetails 查询并为您的查询获取道具“planetID”。

    我知道这不是最好的例子,希望它有所帮助。

    【讨论】:

      【解决方案2】:

      在您 return JSX 之前,在您的 EmploymentReferencePresetEntity 中进行并解决第二次调用可能有助于您的目的。像这样:

      const EmploymentReferencePresetEntity = ({data: {loading, error, nodeQuery}}) => {
        if (loading) {
          return <p>Loading...</p>;
        }
        if (error) {
          return <p>{error.message}</p>;
        }
      
        ... make and resolve your second query here like...
        const secondQueryResult = await secondQuery(nodeQuery)
      
        return (
          <div>
            //do something with secondQueryResult
          </div>
        )
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        • 1970-01-01
        • 2021-01-15
        • 2020-01-20
        • 1970-01-01
        • 2018-05-30
        相关资源
        最近更新 更多