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

在React中如何通过Axios GET请求的URL传递state存储的状态值?

问题原因

你遇到的问题是异步操作执行顺序导致的:

  • Axios的GET请求是异步任务,你写在第一个请求后面的第二个请求,会在第一个请求还没拿到接口返回结果时就提前执行,此时empno还没有被存入state
  • React的setState本身也是异步更新的,就算第一个请求已经拿到结果执行了setState,也不会立刻同步更新this.state的值,直接在setState后读取state也会拿到更新前的旧值。

解决方法

方案1:在第一个请求的回调中直接使用返回的empno发起请求(推荐)

不需要等待state更新,直接用第一个接口返回的empno值发起第二个请求,执行效率更高,代码如下:

componentDidMount() {
  this.retrievePosts();
}

retrievePosts() {
  const id = this.props.match.params.id;
  console.log(id);
  axios.get(`http://localhost:5000/employees/${id}`).then(res => {
    if (res.data.success) {
      const empno = res.data.employee.empno;
      // 存储empno到state
      this.setState({
        empno: empno
      });
      // 直接用返回的empno发起第二个请求
      return axios.get(`http://localhost:5000/employees/alocation/${empno}`)
    }
  }).then(res => {
    if (res?.data.success) {
      this.setState({
        totalallocation: res.data.allocationcount
      }, () => {
        // 要拿到更新后的state值需要放到setState的回调中
        console.log(this.state.totalallocation);
      });
    }
  }).catch(err => {
    // 增加错误捕获避免页面崩溃
    console.error('请求出错:', err)
  })
}

方案2:使用setState的回调函数触发第二个请求

如果你必须等state中的empno更新完成后再发起请求,可以把第二个请求放到setState的第二个回调参数中,这个回调会在state更新完成后才触发:

retrievePosts() {
  const id = this.props.match.params.id;
  console.log(id);
  axios.get(`http://localhost:5000/employees/${id}`).then(res => {
    if (res.data.success) {
      this.setState({
        empno: res.data.employee.empno
      }, () => {
        // 回调触发时state已经更新完成,可以正常读取empno
        axios.get(`http://localhost:5000/employees/alocation/${this.state.empno}`).then(res => {
          if (res.data.success) {
            this.setState({
              totalallocation: res.data.allocationcount
            }, () => {
              console.log(this.state.totalallocation);
            });
          }
        })
      });
    }
  }).catch(err => {
    console.error('请求出错:', err)
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:15:01