GraphQL 与 Apollo - 如何使用 fetchMore

Ala*_*jko 3 pagination apollo reactjs graphql apollo-client

我在理解 ApollofetchMore方法时遇到问题。我是这个工具的新手,文档中的示例对我来说太复杂了。我在互联网上搜索,但找不到更多(当前)示例。你能帮我写一个无限加载数据的最简单的例子吗?我有这个代码:

const productInfo = gql`
  query {
    allProducts { 
      id
      name
      price
      category {
        name
      }
    }
  }`

const ProductsListData = graphql(productInfo)(ProductsList)
Run Code Online (Sandbox Code Playgroud)

我想在每次点击“加载更多”按钮后获取 5 个产品和 5 个以上的产品。我理解这个想法 - 光标等,但我不知道如何实现这一点。(我正在使用反应)

Sco*_*son 5

对于无限加载,您将使用游标。参考 Apollo 文档中的示例,http://dev.apollodata.com/react/pagination.html#cursor-pages

根据您提供的架构定制它,它看起来像这样(未经测试)

const ProductsListData = graphql(productInfo, {
  props({ data: { loading, cursor, allProducts, fetchMore } }) {
    return {
      loading,
      allProducts,
      loadMoreEntries: () => {
        return fetchMore({
          variables: {
            cursor: cursor,
          },
          updateQuery: (previousResult, { fetchMoreResult }) => {
            const previousEntry = previousResult.entry;
            const newProducts = fetchMoreResult.allProducts;
            return {
              cursor: fetchMoreResult.cursor,
              entry: {
                allProducts: [...previousEntry.entry.allProducts, ...newProducts],
              },
            };
          },
        });
      },
    };
  },
})(ProductsList);
Run Code Online (Sandbox Code Playgroud)

您可能需要处理对象的路径,因为这应该与您的架构相似。但在大多数情况下,这就是无限滚动分页实现的样子。