接続のレンダリング
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とnodes にクエリを実行できます。通常、edgesにはエンティティ間のリレーションシップに関する情報が含まれており、nodeはリレーションシップの反対側の実際のエンティティです。この例では、nodeはユーザーの友達を表すUserタイプのオブジェクトです。 - Relay にこの接続に対してページャーを実行したいことを伝えるには、
@connectionディレクティブでフィールドをマークする必要があります。また、この接続の一意の静的 ID(keyと呼ばれる)も指定する必要があります。接続キーには、<fragment_name>_<field_name>という命名規則を使用することを推奨します。 - フィールドを
@connectionとしてマークし、一意のkeyを指定する必要がある理由は、接続の更新セクションで詳しく説明します。
接続に対してクエリを実行するこのフラグメントをレンダリングするには、usePaginationFragment フックを使用できます
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タイプにある「再取得可能な」フラグメントにのみ追加できます。
- 2 つの Flow 型パラメータを受け取ります。生成されたクエリ(この例では
FriendsListPaginationQuery)のタイプと、常に推論できる 2 番目のタイプです。アンダースコア(_)を渡す必要があるためです。
このページは役に立ちましたか?
このサイトをさらに改善するには、 簡単な質問に答えてください.