javascript - Javascript - await fetch response
问题描述
I have a React-Native app and when the component mounts, I want to fetch data by calling a method in our services class, wait for that data to be returned, then set that data in setState({}). But setState({}) is called before the data is returned.
//Component class
componentDidMount(){
this.getData();
}
async getData() {
const data = await MyService.getData();
this.setState({
blah:data //undefined
});
}
//Services Class
let MyService = {
getData:function(){
axios.get(url)
.then(response => response.data)
.then((data) => {
//do stuff
return data;//need to set this to state back in component class
})
.catch(error => {
console.log(error);
});
}
}
module.exports = MyService;
解决方案
你必须回axios.get
电话。否则async function
将返回一个空的承诺(带有undefined
值的承诺)。
let MyService = {
getData: function() {
return axios.get(url)
.then(response => response.data)
.then((data) => {
// do stuff
return data; // need to set this to state back in component class
})
.catch(error => {
console.log(error);
});
}
}
如果你返回这个 axios 调用,它本身就是一个承诺,你不会等到它解决,所以没有必要使用async
.
推荐阅读
- google-cloud-platform - 选择最大分区表
- ios - 如何在精灵工具包游戏中仅在场景中显示一次标签
- python - I want to remove certain characters in list in python
- docker - 大三角帆网关端点
- .net - 列出为 .NET 中的 ETW 跟踪事件会话启用的提供程序
- python - Python 关闭进程、线程、管道、队列、定时器
- java - 读取部署在 Kubernetes 上的 Springboot 中的秘密
- swift - 模拟 bigendian 环境或加载 bigendian 模拟器以进行测试
- docker - Docker Desktop (parse :2375: missing protocol scheme)
- vba - 如何从单元格中提取前 n 个字符并将其复制到新工作表中