我是第一次接触React Js,并且尝试使用fetch进行API调用。
我已经编写了一个通用的异步函数,用于API调用,将请求发送到API端点。该函数在另一个类的函数中被调用,它应该解析结果并将值返回给父函数调用。
下面是我的实用程序类,其中包含一个调用端点的函数:
export default class RestUtil {
getModel = async (model) => {
let url = 'http://api.xyz.com/' + model;
const apiCall = await fetch(url,
{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer xyz'
}
});
return apiCall.json();
}
}下面是我的React组件,它导致了问题:
export default class MyComponent extends React.Component {
componentDidMount() {
this.populateUsersDropDown();
}
populateUsersDropDown() {
let users = this.fetchUsers();
// Here the `users` is undefined. <-------- Issue
//Do some other work with users
/*Populate users in
the dropdown*/
}
fetchUsers() {
new RestUtil()
.getModel('users')
.then(data => {
/* Do some other work with data */
return data;
})
}
}现在,我希望populateUsersDropDown()等待fetchUsers()完成它的then部分,并返回数据,然后继续。但是我在用户变量中收到了undefined。在这里,在我的then部分,我能够看到数据。
需要一些帮助来解决这个问题吗?
发布于 2019-11-13 18:27:25
您的fetchUsers方法不返回任何内容。
async fetchUsers() {
const users = await new RestUtil().getModel('users');
return users;
}这应该是可行的
https://stackoverflow.com/questions/58834864
复制相似问题