在 react native flatlist 中使用 Apollo 挂钩的最佳分页实现是什么?

问题描述

我正在寻找有关在使用 apollo 钩子时如何最好地在 flatlist 提供的 onEndReached 回调中实现 loadMore 函数的见解!除了每次我加载更多结果时,我已经得到了它的工作,因为 flatlist 的数据字段依赖于来自 useQuery 的传入数据,每次它要求更多时都会改变...... 我不知道我是否应该实施基于偏移和限制的分页、基于游标或其他一些策略。 如果有人有提示,那将是巨大的!谢谢!

解决方法

我正在使用 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 时才会调用。