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

React调用setState更新页码后发起API请求仍使用count旧值问题

问题原因

React 中setState是异步批量执行的,你在翻页函数中调用setState修改页码后立即发起请求,此时this.state.count还未完成更新,因此请求携带的仍是修改前的旧页码。

修复方案

方案1:使用setState回调(推荐)

setState支持传入第二个参数作为状态更新完成后的回调函数,我们将接口请求放到回调中执行,就能拿到最新的页码值。
只需修改handlePrev和handleNext函数即可:

handlePrev = () => {
  if (this.state.count > 1) {
    this.setState((prevState) => ({
      count: prevState.count - 1
    }), () => {
      // 状态更新完成后再调用接口
      this.handleApi();
    })
  }
};

handleNext = () => {
  if (this.state.count < this.state.data.total) {
    this.setState((prevState) => ({
      count: prevState.count + 1
    }), () => {
      this.handleApi();
    })
  }
};

方案2:直接传递新页码参数

你也可以计算出新页码后,直接作为参数传给接口请求函数,无需等待状态更新完成:

// 改造接口请求函数,支持接收页码参数
handleApi = (targetPage = this.state.count) => {
  fetch(`http://localhost:9000/accounts?page=${targetPage}`)
    .then((res) => res.json())
    .then((res) => {
      this.setState({ data: res });
    })
    .catch((err) => console.log(err));
};

handlePrev = () => {
  if (this.state.count > 1) {
    const newCount = this.state.count - 1;
    this.setState({ count: newCount })
    // 直接传新页码发起请求
    this.handleApi(newCount);
  }
};

handleNext = () => {
  if (this.state.count < this.state.data.total) {
    const newCount = this.state.count + 1;
    this.setState({ count: newCount })
    this.handleApi(newCount);
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:36:04