How to get RelayJS to understand that a response f

2019-02-05 08:18发布

问题:

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.

回答1:

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.