跳到正文
DEV Community· MinPin Proxy·· 1 小時前AI 評分49

無限捲動中重複項目與遺漏項目:分頁錯誤及解決方法

The same item shows up twice in the feed, and another one never shows up. Pagination bugs in infinite scroll.

AI 導讀

無限捲動時,資料新增或刪除會令 offset 分頁的位置移動,導致項目重複或遺漏;排序欄位不唯一也可能造成同樣問題。改用以排序鍵為依據的 cursor(keyset)分頁,並加入唯一排序條件,可避免這類分頁錯誤。客戶端還應按 ID 去重、避免重複載入同一頁,並忽略過期回應。

正文

The bug reports: "I saw the same post twice while scrolling." "A message I know exists never appeared in the list." Both are hard to reproduce, because they only happen when the data changes while someone is scrolling. In production that's all the time.

Usually the cause is the pagination scheme, not the list view. Here's how it goes wrong and what to use instead.

Offset pagination shifts under you

The classic API: GET /items?offset=40&limit=20, sorted newest first.

  • A new item is added at the top between page 2 and page 3. Everything moves down by one. The item that was at position 39 is now at 40, so page 3 starts with an item the user has already seen. Duplicate.
  • An item is deleted above the current position. Everything moves up by one. The item that was at 40 is now at 39, it falls between page 2 and page 3, and the user never sees it. Missing item.

The client did nothing wrong. Offsets describe positions, and positions change.

Sorting that isn't unique

Even without inserts, a sort like ORDER BY created_at DESC is not stable when two rows share the same timestamp. The database can return tied rows in a different order on each query, so a row can land on both page 2 and page 3, or on neither. This happens a lot with bulk imports and with timestamps rounded to the second.

Always add a unique tie-breaker: ORDER BY created_at DESC, id DESC.

Cursor (keyset) pagination

Instead of "skip 40 rows", the client says "give me items after this one":

GET /items?limit=20
→ { "items": [...], "next_cursor": "eyJjIjoiMjAyNi0xMS0yM1QwOTowMDowMFoiLCJpZCI6ODQyfQ" }

GET /items?limit=20&cursor=eyJj...

The cursor encodes the sort key of the last item (here created_at and id), and the server queries WHERE (created_at, id) < (:c, :id) ORDER BY created_at DESC, id DESC LIMIT 20. New items at the top don't move anything after the cursor, and deleted items simply aren't returned.

Practical points:

  • Make the cursor opaque (for example base64-encoded JSON) so clients don't build it themselves and the server can change it later.
  • Return next_cursor: null on the last page. Don't make the client guess from items.count < limit, which is wrong when the server filters rows after the query.
  • Index the sort columns together, or keyset queries get slow on big tables.
  • Don't promise "jump to page 37". Keyset pagination goes forward (and backward with a second cursor), not to arbitrary pages. For feeds that's fine.

The client still needs to protect itself

Even with cursors, a few client habits prevent most of the remaining reports:

  • De-duplicate by ID when appending a page. Keep a set of IDs already in the list, or let the list's diffing (DiffableDataSource, DiffUtil, Paging 3) work with stable IDs.
  • Don't load the same page twice. Scroll-triggered loading often fires again before the first request returns. Track one in-flight request per cursor and ignore triggers while it runs.
  • Ignore stale responses. If the user pulls to refresh while page 4 is loading, the old page 4 response can arrive after the refresh and append to the new list. Tag each request with the list "generation" and drop responses from an older one.
  • New items at the top are a separate request. Fetch "items newer than the first one I have" on refresh, instead of reloading from offset 0 and merging.

On Android, Paging 3 handles in-flight tracking and page keys for you (PagingSource with the cursor as the key). On iOS there's no built-in equivalent, so the in-flight and generation checks are yours to write.

Testing it

These bugs don't show up with a static test database. To reproduce them:

  1. Load the first page in the app.
  2. Insert a few items at the top on the server (or delete a few from the first page).
  3. Scroll to load the next page.
  4. With offset pagination you'll see duplicates (after inserts) or gaps (after deletes). With cursors you shouldn't see either.

Also watch the requests while scrolling fast: you should see each cursor requested once. Two identical page requests a few milliseconds apart mean the in-flight check is missing.


This article was created with the help of AI.

來源:DEV Community · dev.to