【发布时间】:2020-02-29 23:56:19
【问题描述】:
我正在尝试这种方式:-
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。当我获取这些数据时,我必须渲染这些数据。
【问题讨论】:
标签: reactjs async-await axios