reactjs - 如何通过 Promise 从两个 API 中设置数据?(反应.js)
问题描述
考虑下面的代码:
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 值。
解决方案
componentDidMount() {
Promise.all([
fetch(`http://localhost:9000/api/users/view/${loginEmail}`).then(blob => blob.json()),
fetch(`http://localhost:9000/api/event/view/${id}`).then(blob => blob.json())
])
.then([response1, response2] => {
this.setState(prevState => {
// do your operations
return {
...prevState
}
})
})
.catch(error => {
// handle error
})
}
推荐阅读
- macos - 将数据从一个单元格中分离出来,没有分隔符到列
- flutter - TextFormField 在选择图像后忽略任何文本更改
- node.js - 环回nodejs服务器未启动
- javascript - React,gatsbyjs:循环对象 - 组件不会被渲染
- .htaccess - mod_rewrite 错误 500 对于某些没有重写的文件不会给出错误
- javascript - 从请求中解析响应正文并返回给客户端
- security - 如果用户没有电子邮件帐户,则实施密码恢复
- validation - Google 表单中的字段验证有多安全?
- azure - 如何访问 Azure Web Apps For Containers 的持久共享存储
- c# - 在事件处理程序“(作为按钮的发送者).Content”中获取 Xml Content="{Binding XPath=...}"