如何让RelayJS了解GraphQL的响应是一个项目数组,而不仅仅是一个项目

Cam*_*oth 7 graphql relayjs

我有一个GraphQL服务器运行,其架构大致如下:

type Card {
  id: String!
  name: String
}

type Query {
  card(name: String!): Card
  cards(power: String): [Card]
}
Run Code Online (Sandbox Code Playgroud)

请注意,我对单张卡有查询,但也有多张卡.当我使用GraphIQl UI并进行类似"查询{卡片{名称}}的查询"时,我会按预期返回一系列卡片.

但是,我有一个RelayContainer正在进行相同的查询,但返回的道具只是第一个结果,而不是结果数组.

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')}
      }
    `
  },
});
Run Code Online (Sandbox Code Playgroud)

和ListList组件使用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
      }
    `,
  },
});
Run Code Online (Sandbox Code Playgroud)

有人有什么建议吗?这是我潜入GraphQL和Relay的第二天,所以我可能会犯一个非常基本的错误.

win*_*ent 11

您可能需要查询片段的@relay(plural: true)指令cards.在Relay repo 中的星球大战示例中有一个多场的实例.

但是,如果您关心分页,则可能需要连接而不是复数字段.连接在中继文档中描述,并在graphql-relay-js中实现.

  • 现在,您无法在根目录中建立连接.这是一个已知的限制,但我们计划解决它,并且[在此处跟踪]进展(https://github.com/facebook/relay/issues/112).目前,解决方法是将这些东西包装在另一个根域中(例如,`viewer`). (3认同)