在前端开发中,如何处理列表分页时遇到接口延迟或数据返回顺序不一致的问题

1. 加载状态指示

在发送请求时,设置一个加载状态(例如 isLoading),告诉用户正在加载数据。当收到数据后,再更新状态。

2. 取消上一个请求

在发送新的请求之前,可以取消之前的请求。使用像 Axios 的 CancelToken 可以帮助你做到这一点。

3. 保持数据一致性

在每次请求时,保存当前请求的页码,并在数据返回时检查这个页码。只有当返回的数据页码与当前请求的页码一致时,才更新视图。

复制代码
fetchData(page) {
      this.currentPage = page;
      
      // 取消上一个请求
      if (this.cancelTokenSource) {
        this.cancelTokenSource.cancel("Operation canceled due to new request.");
      }

      this.isLoading = true;

      // 创建一个新的取消令牌
      this.cancelTokenSource = axios.CancelToken.source();

      axios.get(`/api/data?page=${this.currentPage}`, {
        cancelToken: this.cancelTokenSource.token,
      })
      .then(response => {
        // 仅在请求的页面与当前页面一致时更新数据
        if (response.data.page === this.currentPage) {
          this.items = response.data.items;
        }
      })
      .catch(error => {
        if (axios.isCancel(error)) {
          console.log("Request canceled:", error.message);
        } else {
          console.error("Error fetching data:", error);
        }
      })
      .finally(() => {
        this.isLoading = false;
      });
    },
相关推荐
23级二本计科几秒前
前端 HTML + CSS + JavaScript
前端·css·html
踩着两条虫1 分钟前
VTJ.PRO「AI + 低代码」应用开发平台的后端模块系统
前端·人工智能·低代码
pany9 分钟前
程序员近十年新年愿望,都有哪些变化?
前端·后端·程序员
大鸡爪11 分钟前
基于PDF.js的安全PDF预览组件实现:从虚拟滚动到水印渲染
vue.js
朱昆鹏13 分钟前
IDEA Claude Code or Codex GUI 插件【开源自荐】
前端·后端·github
HashTang14 分钟前
买了专业屏只当普通屏用?解锁 BenQ RD280U 的“隐藏”开发者模式
前端·javascript·后端
双向3314 分钟前
Agent智能体:2026年AI开发者必须掌握的自主系统革命
前端
мо仙堡杠把子ご灬14 分钟前
【无标题】
javascript
布列瑟农的星空14 分钟前
通用语法校验器tree-sitter——C++语法校验实践
前端
用户812748281512016 分钟前
libgui中的BufferQueueProducer加入堆栈CallStack编译报错问题-大厂企业实战项目难题
前端