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

React中如何从axios的GET接口获取id并在另一POST请求中使用

实现方案

1. 初始化state添加id存储字段

在组件constructor中新增字段,用来存储从get接口拿到的目标id:

constructor(props) {
  super(props);
  this.state = {
    posts: [],
    targetId: '', // 专门存储接口返回的id
    question: '',
    answer: ''
  }
}

2. 修改get请求的成功回调,将id存入state

请根据你接口的实际返回结构取值,以下为示例:如果接口直接返回带id的对象就直接取,如果返回的是列表就按需取对应项的id:

componentDidMount() {
  axios.get(`https://api-test.com/api/get/all`)
  .then(res => {
    const posts = res.data;
    // 按实际返回结构取id,比如返回列表取第一条id就写res.data[0].id
    const getId = res.data.id; 
    this.setState({ posts, targetId: getId });
   })
 }

3. 发post请求时直接从state取id

注意要保证post请求在get请求完成之后触发,避免id还没存入state就发起请求:

// 可以封装成独立的提交方法,比如绑定到表单提交按钮
handleSubmit = () => {
  axios.post('https://api-test.com/api/faqs',
    { 
      getId: this.state.targetId, // 直接读取state里存好的id
      faqList:[
       { 
         question: this.state.question, 
         answer: this.state.answer,
       }
      ]
    }
  )
  .then(res => {
    // 处理post请求成功后的逻辑
  })
}

注意事项

  • axios.get是异步请求,不要在componentDidMount里发完get立刻同步发post,会出现id为空的问题,建议把post的触发放在用户操作(比如按钮点击),或者在get的then回调里调用post方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:57:05