跳至主要內容
版本:v18.0.0

分頁

要實際在連接上執行分頁,我們需要使用 loadNext 函式來獲取下一頁的項目,此函式可從 usePaginationFragment 取得。

import type {FriendsListComponent_user$key} from 'FriendsList_user.graphql';

const React = require('React');

const {graphql, usePaginationFragment} = require('react-relay');

const {Suspense} = require('React');

type Props = {
user: FriendsListComponent_user$key,
};

function FriendsListComponent(props: Props) {
const {data, loadNext} = usePaginationFragment(
graphql`
fragment FriendsListComponent_user on User
@refetchable(queryName: "FriendsListPaginationQuery") {
name
friends(first: $count, after: $cursor)
@connection(key: "FriendsList_user_friends") {
edges {
node {
name
age
}
}
}
}
`,
props.user,
);

return (
<>
<h1>Friends of {data.name}:</h1>
<div>
{(data.friends?.edges ?? []).map(edge => {
const node = edge.node;
return (
<Suspense fallback={<Glimmer />}>
<FriendComponent user={node} />
</Suspense>
);
})}
</div>

<Button
onClick={() => {
loadNext(10)
}}>
Load more friends
</Button>
</>
);
}

module.exports = FriendsListComponent;

讓我們來分析一下這裡發生了什麼

  • loadNext 接收一個計數,以指定要從伺服器獲取連接中多少個項目。 在此案例中,當呼叫 loadNext 時,我們將獲取目前渲染的 User 的朋友清單中接下來的 10 位朋友。
  • 當獲取下一個項目的請求完成時,連接將會自動更新,並且元件將使用連接中的最新項目重新渲染。 在我們的案例中,這表示 friends 欄位將始終包含我們目前為止已獲取的所有朋友。 預設情況下,Relay 會在完成分頁請求後自動將新項目附加到連接,並使其可供您的片段元件使用 如果您需要不同的行為,請查看我們的進階分頁使用案例章節。
  • loadNext 可能會導致元件或新的子元件暫停(如使用 Suspense 的載入狀態中所述)。 這表示您需要確保從上方有一個 Suspense 邊界包裝此元件。

通常,您也會想要存取有關是否還有更多項目可供載入的資訊。 為此,您可以使用 hasNext 值,也可從 usePaginationFragment 取得

import type {FriendsListPaginationQuery} from 'FriendsListPaginationQuery.graphql';
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,
loadNext,
hasNext,
} = usePaginationFragment(
graphql`...`,
props.user,
);

return (
<>
<h1>Friends of {data.name}:</h1>
{/* ... */}

{/* Only render button if there are more friends to load in the list */}
{hasNext ? (
<Button
onClick={/* ... */}>
Load more friends
</Button>
) : null}
</>
);
}

module.exports = FriendsListComponent;
  • hasNext 是一個布林值,指示連接是否還有更多項目可用。 此資訊可用於判斷是否應該渲染不同的 UI 控制項。 在我們的特定案例中,只有當連接中還有更多朋友可用時,我們才會渲染 Button

此頁面是否實用?

請協助我們回答幾個快速問題,讓網站更加完善 回答幾個快速問題.