本文介绍了如何让 RelayJS 理解来自 GraphQL 的响应是一个项目数组,而不仅仅是一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 GraphQL 服务器,其架构大致如下:
type Card {id:字符串!名称:字符串}类型查询{卡(名称:字符串!):卡卡片(权力:字符串):[卡片]}
请注意,我对单张卡有查询,但对多张卡也有查询.当我使用 GraphIQl UI 并进行类似查询 {cards { name }}"这样的查询时,我会按预期返回一组卡片.
但是,我有一个 RelayContainer 正在执行相同的查询,但返回的道具只是第一个结果,而不是结果数组.
class MyApp extends React.Component {使成为() {返回 (<div><h1>世界你好!</h1><CardList card={this.props.cards}/>
);}}导出默认 Relay.createContainer(MyApp, {片段:{卡片:() =>中继.QL`卡片上的片段{名称}`,卡片:() =>中继.QL`卡片上的片段{${CardList.getFragment('cards')}}`},});
CardList 组件与 Container 一起设置如下:
class CardList extends React.Component {使成为() {返回 <div>{this.props.cards}</div>//意外 - this.props.cards 是第一张卡片,不是我要映射的数组}}导出默认 Relay.createContainer(CardList, {片段:{卡片:() =>中继.QL`卡片上的片段{名称}`,},});
有人有什么建议吗?这是我深入研究 GraphQL 和 Relay 的第 2 天,所以据我所知,我可能犯了一个非常基本的错误.
解决方案
您可能需要在 cards
查询片段上使用 @relay(plural: true)
指令.有一个复数字段的例子 在 Star Wars 示例中 在 Relay 存储库中.
不过,如果您关心分页,您可能需要连接而不是复数字段.在中继文档中描述了连接并在.
I have a GraphQL server running with a schema roughly like this:
type Card {
id: String!
name: String
}
type Query {
card(name: String!): Card
cards(power: String): [Card]
}
Notice that I have a query on a single card, but also on multiple cards. When I use the GraphIQl UI and make a query like this "query {cards { name }}" I get back an array of cards, as expected.
However, I have a RelayContainer that is making the same query, but the props that come back are just the first result, rather than an array of results.
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')}
}
`
},
});
and the CardList component is set up with the Container like this:
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
}
`,
},
});
Anybody have any suggestions? This is day 2 of me diving into GraphQL and Relay, so I might be making a very basic mistake for all I know.
解决方案
You probably want a @relay(plural: true)
directive on your cards
query fragment. There is an example of a plural field in action in the Star Wars example in the Relay repo.
If you care about pagination, though, you probably want a connection instead of a plural field. Connections are described in the Relay docs and implemented in graphql-relay-js.
这篇关于如何让 RelayJS 理解来自 GraphQL 的响应是一个项目数组,而不仅仅是一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!