【发布时间】:2020-06-12 16:04:55
【问题描述】:
考虑下面的代码:
componentDidMount(){
const loginEmail = localStorage.getItem('loginEmail');
const id = localStorage.getItem('id');
Promise.all([
fetch(`http://localhost:9000/api/users/view/${loginEmail}`) // first API
.then(value =>
value.json().then((res)=>{
this.setState({data: res.data});
})),
fetch(`http://localhost:9000/api/event/view/${id}`) // Second API
.then(value =>
value.json().then((res)=>{
this.setState({data: res.data});
})),
])
console.log(this.state.data) // cant get the result
.catch((err) => {
console.log(err);
});
}
这就是我从控制台得到的响应
所以我的做法是错误的吗?顺便说一句,我来自 JSON api 的数据是 Object 值。
【问题讨论】:
-
setState是异步的——这就是为什么this.state.data不是您所期望的。看看这个问题:Why calling react setState method doesn't mutate the state immediately?
标签: reactjs api promise setstate