我有一个运行模式的 GraphQL 服务器,大致如下所示:
type Card {
id: String!
name: String
}
type Query {
card(name: String!): Card
cards(power: String): [Card]
}
请注意,我对单张卡进行了查询,但也对多张卡进行了查询。当我使用 GraphIQl UI 并进行类似“查询 {cards { name }}”这样的查询时,我会按预期返回一组卡片。
但是,我有一个 RelayContainer 进行相同的查询,但返回的 Prop 只是第一个结果,而不是结果数组。
class MyApp extends React.Component {
render() {
return (
<div>
<h1> Hello world!</h1>
<CardList cards={this.props.cards} />
</div>
);
}
}
export default Relay.createContainer(MyApp, {
fragments: {
card: () => Relay.QL`
fragment on Card {
name
}
`,
cards: () => Relay.QL`
fragment on Card {
${CardList.getFragment('cards')}
}
`
},
});
CardList 组件与 Container 一起设置,如下所示:
class CardList extends React.Component {
render() {
return <div>{this.props.cards}</div> // UNEXPECTED - this.props.cards is the first card, not an array for me to .map over
}
}
export default Relay.createContainer(CardList, {
fragments: {
cards: () => Relay.QL`
fragment on Card {
name
}
`,
},
});
有人有什么建议吗?这是我深入研究 GraphQL 和 Relay 的第 2 天,所以就我所知,我可能犯了一个非常基本的错误。
最佳答案
您可能想要一个 @relay(plural: true)
您的 cards
上的指令查询片段。有一个复数字段的例子in the Star Wars example在中继仓库中。
但是,如果您关心分页,您可能需要连接而不是复数字段。连接描述 in the Relay docs并在 graphql-relay-js 中实现.
关于graphql - 如何让 RelayJS 理解来自 GraphQL 的响应是一个项目数组,而不仅仅是一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32491117/