微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 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 时才会调用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。