React.js中如何通过Promise处理两个API数据并执行setState?
问题分析与修复方案
Let's break down the issues in your code step by step:
1. 同步代码提前执行,无法获取异步结果
你在Promise.all()之后直接调用console.log(this.state.data),但这个console.log是同步执行的——此时两个API请求还没完成,setState也还没更新状态,自然拿不到预期结果。而且setState本身也是异步操作,就算请求完成,也不能立刻拿到更新后的state。
2. 两个请求的结果互相覆盖
两个API请求都用this.setState({data: res.data})更新同一个state.data,后完成的请求会直接覆盖先完成的那个结果,导致你最终只能拿到其中一个接口的数据。
3. Promise.all的语法错误
你的代码里console.log插在了Promise.all()和.catch()之间,破坏了Promise的链式调用结构,这会导致语法错误,catch也无法正确捕获Promise链里的异常。
修复后的代码示例
componentDidMount(){ const loginEmail = localStorage.getItem('loginEmail'); const id = localStorage.getItem('id'); Promise.all([ // 第一个请求:获取用户数据 fetch(`http://localhost:9000/api/users/view/${loginEmail}`) .then(response => response.json()), // 第二个请求:获取事件数据 fetch(`http://localhost:9000/api/event/view/${id}`) .then(response => response.json()) ]) .then(([userRes, eventRes]) => { // 把两个请求的结果分别存入state,避免覆盖 this.setState({ userData: userRes.data, eventData: eventRes.data }, () => { // 在setState的回调里获取更新后的state(因为setState是异步的) console.log('用户数据:', this.state.userData); console.log('事件数据:', this.state.eventData); }); }) .catch((err) => { console.error('请求出错:', err); }); }
关键改动说明
- 将两个
fetch的json()解析步骤统一放到Promise.all的链式调用里,这样可以在then里一次性拿到两个请求的结果 - 把两个接口的数据分别存入不同的state字段(
userData和eventData),避免互相覆盖 - 把
console.log放到setState的回调函数里,确保能拿到更新后的状态 - 修正了Promise链式调用的结构,让
catch能正确捕获所有请求的异常
内容的提问来源于stack exchange,提问作者koko ka
相关产品推荐
相关产品推荐

