Fetch additional data for a single item in a list query

£可爱£侵袭症+ 提交于 2019-12-06 05:46:59

Yes, you can fetch multiple fragments per component. My suggestion here would be to have a separate fragment for the selected post, and to make use of it in a route dedicated for the post's detail (permalink) view.

First, add a fragment to represent the selected post.

export default Relay.createContainer(PostList, {
  initialVariables: {
    count: 10,
  },
  fragments: {
    selectedPost: () => Relay.QL`
      fragment on Post {
        id
        title
        description
      }
    `,
    viewer: () => Relay.QL`
      fragment on Viewer {
        posts(first: $count) {
          edges {
            node {
              id
              title
            }
          }
        }
      }
    `,
  },
});

Then create two routes. One will represent only the index view's queries, and one the permalink view's queries.

class IndexRoute extends Relay.Route {
  static queries = {
    viewer: () => Relay.QL`query { viewer }`,
  };
  static routeName = 'IndexRoute';
}

class PostPermalinkRoute extends Relay.Route {
  static queries = {
    selectedPost: () => Relay.QL`query { node(id: $postID) }`,
    viewer: () => Relay.QL`query { viewer }`,
  };
  static paramDefinitions = {
    // By setting `required` to true, `PostPermalinkRoute` 
    // will throw if a `postID` is not supplied when instantiated.
    postID: {required: true},
  };
  static routeName = 'PostPermalinkRoute';
}

Now, you need to write some code that rerenders the app with a new route when you want to switch between the index and the permalink views. By default, Relay will keep rendering the old route while the data for the next route loads, so you should be able to perform your transitions while you wait on the data.

function render(route) {
  ReactDOM.render(
    <Relay.RootContainer
      Component={PostList}
      route={route}
    />,
    container,
  );
}

// When it's time to render the index...
render(new IndexRoute());

// Upon selecting a post...
render(new PostPermalinkRoute({postID: 123}));

The current route is available to you as this.props.relay.route, so you should be able to make some inferences about what state you should be in using this.props.relay.route.name and this.props.relay.route.params.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!