使用 WPGraphQL 在 Headless WordPress 中分页

问题描述 投票:0回答:1

目前在 WordPress 中,我可以在页面分页上加载产品,以在 url 中写入,如

page/2 page/3

现在我尝试在 next.js 应用程序中首先对所有产品进行计数,然后通过切换页面(如 1 2 3 等)以相同的方式显示分页和加载产品。

但是我目前看到的我可以在 wpgraphql 中仅传递下一页,例如:

query MyQuery {
  products(first: 25, after: "YXJyYXljb25uZWN0aW9uOjMxOTQy") {
    pageInfo {
      hasNextPage
      hasPreviousPage
      endCursor
      startCursor
    }
    nodes {
      date
      id
      name
    }
  }
}

任何人都可以帮助我如何获得可能通过页面示例 3 的最终结果,然后在此页面中加载产品。

这是我当前的代码:

export const useProductsData = () => {
  const params = useParams()
  const { handle } = params;

  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchProductsData = async () => {
    const query = gql`
    query {
      products(where: { categoryIn: "${handle}", stockStatus: IN_STOCK }, first: 25) {
        nodes {
          id
          sku
          slug
          status
          name
          image {
            sourceUrl
          }
          ... on SimpleProduct {
            id
            name
            price
          }
          ... on VariableProduct {
            id
            name
            price
          }
        }
      }
    }
  `;
  


    try {
      const result = await fetchWooCommerceData(query);
      setProducts(result.products.nodes);
      setLoading(false);
    } catch (error) {
      setError(error);
      setLoading(false);
    }
  };

  // Call fetchProductData directly when the hook is invoked
  fetchProductsData();

  return { products, loading, error };
};

我找到了插件: https://github.com/valu-digital/wp-graphql-offset-pagination

但看起来上面的内容仅适用于用户和帖子。

我尝试注册产品:

 // Register offsetPagination fields for WooCommerce products
    register_graphql_field(
        'RootQueryToProductConnectionWhereArgs',
        'offsetPagination',
        [
            'type' => 'OffsetPagination',
            'description' => 'Paginate products with offsets',
        ]
    );
}

现在当我查询时:

query Products {
  products(where: { offsetPagination: { size: 10, offset: 30 } }) {
    pageInfo {
      offsetPagination {
        hasMore
        hasPrevious
        total
      }
    }
    nodes {
      id
      name
      # Other product fields
    }
  }
}

我看到输出:

{
  "data": {
    "products": {
      "pageInfo": {
        "offsetPagination": {
          "hasMore": true,
          "hasPrevious": true,
          "total": 16300
        }
      },
      "nodes": [

但是当我更改页面偏移量时仍然加载相同的产品。

reactjs wordpress next.js pagination
1个回答
0
投票

在 Next.js 代码中,您应该管理当前页面状态并确保 fetchProductsData 函数使用此状态来计算 GraphQL 查询的正确偏移量。

这是您可以尝试的代码

export const useProductsData = () => {
  const params = useParams();
  const { handle } = params;

  const [currentPage, setCurrentPage] = useState(1);
  const productsPerPage = 25;
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchProductsData = async (page) => {
    const offset = (page - 1) * productsPerPage;
    const query = gql`
      query {
        products(where: { categoryIn: "${handle}", stockStatus: IN_STOCK, offsetPagination: { size: ${productsPerPage}, offset: ${offset} } }) {
          pageInfo {
            offsetPagination {
              hasMore
              hasPrevious
              total
            }
          }
          nodes {
            id
            sku
            slug
            status
            name
            image {
              sourceUrl
            }
            ... on SimpleProduct {
              id
              name
              price
            }
            ... on VariableProduct {
              id
              name
              price
            }
          }
        }
      }
    `;

    try {
      const result = await fetchWooCommerceData(query);
      setProducts(result.products.nodes);
      setLoading(false);
    } catch (error) {
      setError(error);
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProductsData(currentPage);
  }, [currentPage]);

  return { products, loading, error, setCurrentPage };
};
© www.soinside.com 2019 - 2024. All rights reserved.