分页加载的核心是按需获取、动态追加,需维护page、hasMore、loading状态,通过滚动监听触发fetch请求并拼接数据,注意防重复、防错乱、状态同步。
分页加载的核心是“按需获取、动态追加”,不是一次性拉完再切片,而是每次请求一页数据,成功后拼接到已有列表中。关键在于维护好页码状态、避免重复请求、处理加载中与失败状态。
前端需要主动跟踪当前页码、是否还有下一页、是否正在加载等状态,不能依赖后端返回的 total(除非必须做页码导航):
has_more: true 或 next_page: 2 等)以滚动到底部自动加载为例,每次请求成功后将新数据 push 或 concat 到原数组:
let dataList = []; let page = 1; const pageSize = 10; let hasMore = true; let loading = false;async function loadMore() { if (loading || !hasMore) return;
loading = true; try { const res = await fetch(
/api/list?page=${page}&size=${pageSize}); const { data, has_more } = await res.json();// 拼接数据:直接 push 或用 concat 生成新数组(推荐后者,便于 React/Vue 响应式更新) dataList = dataList.concat(data); hasMore = has_more; page++;} catch (err) { console.error("加载失败", err); } finally { loading = false; } }
3. 滚动监听触发加载(防抖 + 判定底部)
监听容器滚动,当距离底部一定距离(如 100px)且未加载中时触发:
function onScroll() { const container = document.getElementById('list-container'); const { scrollTop, scrollHeight, clientHeight } = container; if (scrollHeight - scrollTop - clientHeight <= 100) { loadMore(); } }// 添加节流(简单实现) let throttleTimer; container.addEventListener('scroll', () => { if (throttleTimer) return
; throttleTimer = setTimeout(() => { onScroll(); throttleTimer = null; }, 150); });
4. 注意事项与常见坑
AbortController(进阶)has_more: true、total: 123 或 next_cursor: "abc123",比单纯靠 length 判断更可靠不复杂但容易忽略的是状态同步——dataList 更新后,视图必须响应;hasMore 变为 false 后要停止监听或禁用加载提示。只要把页码、数据、开关三者串起来,分页加载就稳了。