2015-09-14 104 views
4

支持当你定义的字段为两种类型的工会(在例如机载船舶和Droid),那么在继电器,你可以做这样的事情:联盟类型继电器

fragment on [email protected] relay(plural: true) { 
    name, 
    machines { 
    ... on Ship { 
     name 
    } 
    ... on Droid { 
     name, 
     primaryFunction 
    } 
    } 
} 

所以在机器支撑你的对象是正确的评估,但如果你想这样做,使用碎片从外部组件:

fragment on [email protected] relay(plural: true) { 
    name, 
    machines { 
    ${StarWarsShip.getFragment('ship')} 
    ${StarWarsDroid.getFragment('droid')} 
    } 
} 

那么你最终下机片段定义。它看起来像你被困,并且无法检查哪个对象是机器数组中的哪个类型,所以你不能决定应该使用哪个组件。

+0

https://github.com /脸书/继电器/问题/ 268 – jzalucki

回答

8

存在一个__typename场与您应该能够反思每一个记录类型:

查询

fragment on Faction @relay(plural: true) { 
    name, 
    machines { 
    __typename # <-- add this 
    ${StarWarsShip.getFragment('ship')} 
    ${StarWarsDroid.getFragment('droid')} 
    } 
} 

应用程序代码

this.props.faction.machines.map(machine => 
    machine.__typename === 'Droid' 
    ? <Droid droid={machine} /> 
    : <Ship ship={machine} /> 
); 
+0

...截至https://github.com/facebook/relay/commit/ea2f5faae753526e1a76e70b05d262c4b2662570 – steveluscher

+0

我遇到这个问题,当我尝试像你写的那样做: 未捕获的错误:GraphQL验证/转换错误类型未定义没有字段__typename。 –

+0

什么版本的Relay,以及您正在运行的Babel Relay插件的版本是什么? – steveluscher