1

我的 CMS 向我返回了一个节点列表,每个节点都有自己的节点类型。对于每个节点类型,我定义了一个相应的 GraphQL 类型。

type getContent {
  content: [ContentNode]
}

我想要一个像这样的查询:

{
  content{
    contentType
    properties {
       ${ContentType.getFragment('content', type: $contentType???)}
    }
  }
}

ContentType 将根据提供给它的类型变量返回正确的片段定义。但是我如何$contentType从父级结果中获得?

4

1 回答 1

2

您不能拥有依赖于父级实际值的片段,因为片段是在实际向服务器发出查询请求之前组成的。有两种不同的方法来处理这个问题,一种是让片段根据变量而变化,另一种是在组件中使用接口和类型化片段。

这是一个很好的答案,显示了使用变量的示例:Conditional Fragments or embedded root-containers when using Relay with React-Native

对于接口解决方案,如果您有 ContentNode 的接口,该接口具有“ContentNode1”和“ContentNode2”等实现,那么您可以执行以下操作:

{
  content {
    ${ContentType.getFragment('content')}
  }
}

在您的 ContentType 组件中

fragment on ContentNode {
   contentType
   someOtherCommonField
   ... on ContentNode1 {
     someContent1Field
   }

   ... on ContentNode2 {
     someContent2Field
   }
}
于 2016-04-18T11:43:19.660 回答