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
相关产品推荐
相关产品推荐

