React+Django项目API分页调用逻辑异常求助
分页API调用逻辑修正方案
核心问题:当前页码转换逻辑错误。正确规则是用户点击第
N页时,需调用的起始页为2 * N - 1,结束页为2 * N。你现在的代码应该是直接将用户点击的N作为起始页,再加1得到结束页,才会出现点击第2页调用page=2和page=3的情况。基于while循环的正确实现示例:
假设用户点击的页码变量为userPage,代码逻辑如下:// 计算目标页码范围 let startPage = 2 * userPage - 1; let endPage = 2 * userPage; let currentPage = startPage; // 循环调用API while (currentPage <= endPage) { // 替换为你的实际API请求逻辑(比如axios/fetch) fetch(`/api/your-resource/?page=${currentPage}`) .then(response => response.json()) .then(data => { // 处理每页返回的数据 console.log(`加载第${currentPage}页数据`, data); }) .catch(error => console.error(`请求第${currentPage}页失败`, error)); currentPage++; }额外排查点:
- 确认
userPage参数传递是否正确,比如点击第2页时,该变量是否确实为2,而非被错误处理为1。 - 检查后端Django接口是否正确接收
page参数,避免参数名拼写错误(比如误用p或page_num)。
- 确认
内容的提问来源于stack exchange,提问作者Dana
相关产品推荐
相关产品推荐

