You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React自定义分页含下拉选择,出现额外-1页码问题求助

Troubleshooting the "-1 Page Number" Bug in Your React Pagination Component

Hey there! As a fellow React dev who's wrestled with pagination bugs before, I totally get how frustrating this is. Let's break down what's likely going on and how to fix it:

Key Observations About the Bug

The "-1" page number popping up when switching page sizes (especially from a larger size's last page back to a smaller one) points to two common issues:

  • Out-of-sync state between your current page and the new total pages after changing the page size
  • Missing boundary checks in your page number generation loop

Step-by-Step Troubleshooting & Fixes

1. Fix State Sync When Changing Page Size

When you switch to a smaller page size from the last page of a larger size, even if your current page seems valid for the new size, stale state values or incorrect updates can lead to wonky calculations later. Add this logic to your page size change handler:

const handlePageSizeChange = (newPageSize) => {
  // Calculate the new total pages first
  const newTotalPages = Math.ceil(totalData / newPageSize);
  // Make sure current page doesn't exceed the new total pages
  const updatedCurrentPage = Math.min(currentPage, newTotalPages);
  
  // Update state with the corrected values
  setPageSize(newPageSize);
  setCurrentPage(updatedCurrentPage);
};

If you want to avoid stale state issues, use functional state updates instead:

const handlePageSizeChange = (newPageSize) => {
  setPageSize(newPageSize);
  setCurrentPage(prevPage => {
    const newTotalPages = Math.ceil(totalData / newPageSize);
    return Math.min(prevPage, newTotalPages);
  });
};

2. Add Hard Boundary Checks in Your Page Number Loop

Your suspicion about the pagination loop is spot-on. The "-1" happens because your loop is generating a number below 1—probably when calculating the starting page for your pagination links.

For example, if your code calculates the starting page like currentPage - 2 (to show 2 sibling pages on either side), when currentPage is 1, that gives you -1. You need to clamp that value to be at least 1.

Here's a safe way to generate page numbers with boundary guards:

const generatePageNumbers = () => {
  const totalPages = Math.ceil(totalData / pageSize);
  const siblingCount = 2; // Adjust based on how many siblings you want to show
  const pages = [];

  // Calculate start/end pages with boundary checks
  let startPage = Math.max(currentPage - siblingCount, 1);
  let endPage = Math.min(currentPage + siblingCount, totalPages);

  // Add first page and ellipsis if needed
  if (startPage > 2) pages.push(1);
  if (startPage > 3) pages.push('...');

  // Add middle pages (this is where -1 was sneaking in before!)
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i);
  }

  // Add last page and ellipsis if needed
  if (endPage < totalPages - 1) pages.push('...');
  if (endPage < totalPages) pages.push(totalPages);

  return pages;
};

The Math.max(startPage, 1) ensures you never go below the first page, and Math.min(endPage, totalPages) keeps you from exceeding the last page.

3. Log State Values to Debug

Add console logs in your page size change handler and pagination loop to see exactly what's happening:

console.log('Before change:', { currentPage, pageSize, totalPages: Math.ceil(totalData / pageSize) });
// After updating state
console.log('After change:', { currentPage, pageSize, totalPages: Math.ceil(totalData / pageSize) });

This will show you if your state is updating correctly, or if the total pages calculation is off (unlikely, but possible if totalData is changing unexpectedly).

4. Ensure totalData is Stable

Double-check that your totalData value isn't being modified accidentally when switching page sizes. If it's fetched from an API, make sure it's not refetching incorrectly (though your bug description doesn't mention data changing, so this is a secondary check).

Final Notes

Most of the time, this bug is fixed by either syncing your current page state properly when changing page sizes, or adding those critical boundary checks in your page number loop. If you share a snippet of your actual pagination loop code, I can help pinpoint the exact line causing the "-1"!

内容的提问来源于stack exchange,提问作者lwchang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:54:42