是的,您可以为每个组件获取多个片段。我的建议是为所选帖子提供一个单独的片段,并在专门用于帖子详细信息(永久链接)视图的路线中使用它。
首先,添加一个片段来表示所选帖子。
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
}
}
}
}
`,
},
});
然后创建两条路由。一个仅代表索引视图的查询,另一个代表永久链接视图的查询。
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';
}
现在,您需要编写一些代码,当您想要在索引视图和永久链接视图之间切换时,使用新路由重新呈现应用程序。默认情况下,Relay 将在加载下一个路由的数据时继续渲染旧路由,因此您应该能够在等待数据时执行转换。
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}));
当前路线可供您使用this.props.relay.route
,所以你应该能够对你应该使用的状态做出一些推断this.props.relay.route.name
and this.props.relay.route.params
.