渲染连接
在 Relay 中,为了显示由 GraphQL 连接支持的数据列表,您首先需要声明一个查询连接的片段。
const {graphql} = require('RelayModern');
const userFragment = graphql`
fragment UserFragment on User {
name
friends(after: $cursor, first: $count)
@connection(key: "UserFragment_friends") {
edges {
node {
...FriendComponent
}
}
}
}
`;
- 在上面的例子中,我们查询的是
friends
字段,它是一个连接;换句话说,它符合连接规范。具体来说,我们可以查询连接中的edges
和node
;edges
通常包含有关实体之间关系的信息,而node
是关系另一端的实际实体;在本例中,node
是表示用户朋友的User
类型对象。 - 为了指示 Relay 我们希望对该连接执行分页,我们需要使用
@connection
指令标记该字段。我们还必须为此连接提供一个静态的唯一标识符,称为key
。我们推荐以下连接键命名约定:<fragment_name>_<field_name>
。 - 在我们的 更新连接 部分,我们将详细介绍为什么需要将该字段标记为
@connection
并为其提供一个唯一的key
。
为了渲染这个查询连接的片段,我们可以使用 usePaginationFragment
Hook。
import type {FriendsListComponent_user$key} from 'FriendsList_user.graphql';
const React = require('React');
const {Suspense} = require('React');
const {graphql, usePaginationFragment} = require('react-relay');
type Props = {
user: FriendsListComponent_user$key,
};
function FriendsListComponent(props: Props) {
const {data} = usePaginationFragment(
graphql`
fragment FriendsListComponent_user on User
@refetchable(queryName: "FriendsListPaginationQuery") {
name
friends(first: $count, after: $cursor)
@connection(key: "FriendsList_user_friends") {
edges {
node {
...FriendComponent
}
}
}
}
`,
props.user,
);
return (
<>
{data.name != null ? <h1>Friends of {data.name}:</h1> : null}
<div>
{/* Extract each friend from the resulting data */}
{(data.friends?.edges ?? []).map(edge => {
const node = edge.node;
return (
<Suspense fallback={<Glimmer />}>
<FriendComponent user={node} />
</Suspense>
);
})}
</div>
</>
);
}
module.exports = FriendsListComponent;
usePaginationFragment
的行为与useFragment
相同(参见 片段 部分),因此我们的朋友列表在data.friends.edges.node
中可用,如片段所声明。但是,它还有一些额外的功能。- 它期望一个带有
@connection
指令注释的连接字段的片段。 - 它期望一个带有
@refetchable
指令注释的片段。请注意,@refetchable
指令只能添加到“可重新获取”的片段中,也就是说,在Viewer
上、在Query
上、在任何实现Node
的类型上(即具有id
字段的类型)或在@fetchable
类型上。
- 它期望一个带有
- 它接受两个 Flow 类型参数:生成的查询的类型(在本例中为
FriendsListPaginationQuery
),以及第二个类型,该类型总是可以推断出来,因此您只需要传递下划线 (_
)即可。
此页面有用吗?
通过以下方式帮助我们改进网站: 回答几个快速问题.