メインコンテンツにスキップ
バージョン: v18.0.0

接続のレンダリング

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 フィールドに対してクエリを実行しています。つまり、接続仕様に準拠しています。具体的には、接続内の edgesnodes にクエリを実行できます。通常、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;
  • usePaginationFragmentuseFragment と同じように動作します(フラグメントセクションを参照)。そのため、data.friends.edges.node には、フラグメントで宣言されたとおり、友達のリストが格納されています。ただし、他の要素もいくつかあります
    • @connection ディレクティブでアノテーションされた接続フィールドのフラグメントを想定しています。
    • @refetchable ディレクティブでアノテーションされたフラグメントを想定しています。なお、@refetchable ディレクティブは、ViewerQueryNode を実装する任意のタイプ(つまり、id フィールドを持つタイプ)、または @fetchable タイプにある「再取得可能な」フラグメントにのみ追加できます。
  • 2 つの Flow 型パラメータを受け取ります。生成されたクエリ(この例では FriendsListPaginationQuery)のタイプと、常に推論できる 2 番目のタイプです。アンダースコア(_)を渡す必要があるためです。

このページは役に立ちましたか?

このサイトをさらに改善するには、 簡単な質問に答えてください.