当使用useLazyQuery和FetchMore进行偏移分页时,需要使用useState hook来跟踪偏移量。这是因为useLazyQuery只会在首次调用时执行,而不会再次执行,而偏移量需要不断更新。
下面是一个示例代码,演示如何使用useState和FetchMore来实现偏移分页:
import React, { useState } from 'react';
import { useLazyQuery } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';
const GET_USERS = gql`
query getUsers($offset: Int, $limit: Int) {
users(offset: $offset, limit: $limit) {
id
name
email
}
}
`;
const UserList = () => {
const [offset, setOffset] = useState(0);
const [limit] = useState(10);
const [getUsers, { data, loading, fetchMore }] = useLazyQuery(GET_USERS);
const loadMore = () => {
fetchMore({
variables: {
offset: offset + limit,
limit
},
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) return prev;
return {
users: [...prev.users, ...fetchMoreResult.users]
};
}
});
setOffset(offset + limit);
};
return (
{data?.users.map(user => (
-
Name: {user.name}, Email: {user.email}
))}
{loading && Loading...
}
);
};
export default UserList;