我正在使用 Shopify 店面 graphql 查询来获取产品列表,以下是我如何在 FlatList 上使用基于光标的分页方法实现分页。希望你能找到一些有用的东西。
首先,声明两个变量,稍后将用于检查 Flatlist 是否滚动并到达末尾。
// declare these two variables
let isFlatlistScrolled = false;
let onEndReachedCalledDuringMomentum = false;
现在,创建一个名为 handleFlatlistScroll 的方法,用于在滚动平面列表时更改变量 isFlatlistScrolled 的值。
const handleFlatlistScroll = () => {
isFlatlistScrolled = true;
};
同时声明一个方法来改变onEndReachedCalledDuringMomentum的值。
const onMomentumScrollBegin = () => {
onEndReachedCalledDuringMomentum = false;
}
现在,像这样创建您的平面列表:
return (
<Layout style={{ flex: 1 }}>
<Query
query={GET_PRODUCT_LIST_BY_COLLECTION_HANDLE}
variables={{
handle: props.route.params.handle,
cursor: null,
}}>
{({
loading,
error,
data,
fetchMore,
networkStatus,
refetch,
stopPolling,
}) => {
if (loading) {
return <ProductListPlaceholder />;
}
if (data && data.collectionByHandle?.products?.edges?.length > 0) {
stopPolling();
return (
<FlatList
data={data.collectionByHandle.products.edges}
keyExtractor={(item, index) => item.node.id}
renderItem={renderProductsItem}
initialNumToRender={20}
onScroll={handleFlatlistScroll}
onEndReached={() => {
if (
!onEndReachedCalledDuringMomentum &&
isFlatlistScrolled &&
!isLoadingMoreProducts &&
!loading &&
data.collectionByHandle?.products?.pageInfo?.hasNextPage
) {
onEndReachedCalledDuringMomentum = true;
setLoadingMoreProductsStatus(true);
// your loadmore function to fetch more products
}
}}
onEndReachedThreshold={Platform.OS === 'ios' ? 0 : 0.1}
onMomentumScrollBegin={onMomentumScrollBegin}
// ... your other flatlist props
/>
);
}
return <EmptyProductList />;
}}
</Query>
</Layout>
)
正如你在上面的代码中看到的,加载更多的函数只有在 flatlist 在最后正确滚动时才会调用。