【问题标题】:Introspection query for EnumValues as a GraphQL fragment in react-componentEnumValues 的自省查询作为 react-component 中的 GraphQL 片段
【发布时间】:2017-11-29 03:17:14
【问题描述】:

我正在使用带有 Relay Schema 的 GraphQL(托管在 graph.cool 上)构建一个 React Native 应用程序。 我在顶级组件中有一个 QueryRenderer,它使用片段为展示组件获取数据,这工作正常。

我的问题:我想做一个自省查询来获取可能的枚举值作为列表,用于我的架构中的特定字段,并在片段旁边获取这些值。 我当前的片段查询:

query ReportingContainerQuery {
    viewer {
        ...MainList_items
           ...
    }
}

MainList_items 片段:

fragment AnimalList_items on Viewer {
    allAnimalCategories {
        edges {
            node{
                id
                ...AnimalListRow_item
            }
        }
    }
}

我得到了以下查询,用于通过自省获取 enumValues(使用:https://www.graph.cool/forum/t/how-to-access-the-possible-values-of-an-enum-type-created-inside-the-console/23/2):

query {
    __type(name: "JOURNAL_ENTRY_GENDER") {
        enumValues {
            name
        }
    }
}

但我似乎无法找到一种方法来创建可以添加到顶级查询的片段。 我可以将内省直接粘贴到顶级查询中,但据我了解,这对中继框架起作用。由于这样做,我将不得不将结果作为道具显式传递,而不是让演示组件指定它需要什么并将其作为片段提供给顶层的 QueryRenderer 并让中继框架隐式传递查询结果到组件。

【问题讨论】:

    标签: react-native enums graphql relayjs


    【解决方案1】:

    经过一番修补后,我找到了解决它的方法 - 它留下了两个地方来维护片段查询,但这是我发现解决它的唯一方法。 :)

    在我的组件中,我定义了以下片段:

    fragment GenderTile_items on __Type {
      enumValues{
        name
      }
    }
    

    然后在我的主容器中,我使用以下内容扩展了 QueryRenderer 中的查询

    query ReportingContainerQuery {
      viewer {
        ...MainList_items
           ...
      }
    
      __type(name: "JOURNAL_ENTRY_GENDER"){
         ...GenderTile_items
      }
    }
    

    然后通过将“props.__type”向下传递到具有相应片段的组件并从那里访问 props.items.enumValues (因为数据的 prop 定义为片段中的“项目”(例如,遵循命名约定“文件名_propName”时的 GenderTile_项目。(https://facebook.github.io/relay/docs/fragment-container.html#data-dependencies-with-graphql))。

    然后我遇到了一个问题,我想获取不止一种类型的枚举,并且查询返回了一个错误,带有重复的 __type 分配。这可以通过使用别名来解决这个问题:

    query ReportingContainerQuery {
      viewer {
        ...MainList_items
           ...
      }
    
      genderEnums: __type(name: "JOURNAL_ENTRY_GENDER"){
         ...GenderTile_items
      }
    
      otherEnums: __type(name: "JOURNAL_ENTRY_OTHER"){
         ...OtherComponent_items
      }
    }
    

    然后可以通过 props.[alias] 获得数据(例如“props.genderEnums”和“props.otherEnums”),然后将其传递给带有片段的组件,并如上所述通过 props.items.enumValues 访问它.

    希望这对遇到与我相同问题的其他人有意义。 :D

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-02
      • 2021-09-05
      • 2019-10-02
      • 2023-01-29
      • 2021-12-22
      • 2018-01-12
      • 2019-02-05
      • 2021-06-14
      相关资源
      最近更新 更多