reactjs - Axios如何在componentDidMount中异步获取数据
问题描述
我正在尝试这种方式:-
state = {
profiles: [],
data: []
}
async componentDidMount() {
try {
// this commented code works. But I want to use axios api.
// const response = await fetch(`http://localhost:8080/all/profile`);
// const json = await response.json();
// this.setState({ data: json });
// const json = await response.json();
let response = await CurdApi.getAllProfiles(); // response always undefined.
this.setState({ data: response });
} catch (error) {
console.log(error);
}
}
我的 CurdApi 课程在这里:-
export default class CurdApi {
static async getAllProfiles() {
await axios({
url: 'http://localhost:8080/all/profile',
method: 'GET',
responseType: 'json',
})
.then((response) => {
return response.data;
})
.catch((error) =>{
return error.data;
});
}
}
我是 ReactJs 和 JS 的新手。我不明白如何正确使用这个 async/await。当我获取这些数据时,我必须渲染这些数据。
解决方案
不要使用await
和then
。
export default class CurdApi {
static async getAllProfiles() {
return await axios({
url: 'http://localhost:8080/all/profile',
method: 'GET',
responseType: 'json',
})
}
}
推荐阅读
- testing - 使用 Cypress 对未存根的路由强制错误
- sql - 如何在 BigQuery 中使用 REGEXP_EXTRACT 仅提取数值?
- javascript - 向客户端发送二进制 blob(带有 XML 文件)时遇到的问题
- c - 如何解决 Visual Studio 2019 中的致命错误 c1083?
- php - 用给定字符串中的动态日期格式替换日期
- javascript - Puppeteer npm 如何从本地文件设置字体
- java - 如何在旅行时获取位置更新以跟踪其他设备的时间?
- react-native - 易受 OpenSSL 库中未来漏洞的影响
- sql - 存储过程错误算术溢出错误将数字转换为数据类型 varchar
- python - 通过 logging.exception() 打印异常时出现异常