如何等待React功能的结果?
我正在尝试从端点获取信息,并将其分配给本地变量。问题在于,该信息已成功获取,当我将Console.Log(resp.data)打印时,我将其打印,因此我将其分配给学院,但是在以下行中,我是一个空的阵列。我尝试了异步/等待 - >我将showoptions的功能定义为异步和等待的教师。我该如何解决这个问题?
const showOptions = () => {
let faculties = [];
facultiesService.getAllFaculties()
.then(async (resp) => {
faculties = await resp.data;
})
.catch(e => console.log(e));
console.log(faculties)
return faculties.map(faculty => {
return <option
key={faculty.id}
value={faculty.id}
>{faculty.name}
</option>
});
}
const showFacultySelect = () => {
return (
<Form.Select aria-label="Default select example">
{showOptions()}
</Form.Select>
)
}
I am trying to fetch info from an endpoint and assign it to a local variable. The problem is that the info is fetched successfully and when I put console.log(resp.data) it is printed, so I assign it to the faculties, but in the following line faculties is an empty array. I tried async/await -> I defined showOptions function as async and awaited facultiesService.getAllFaculties(), but the problem was not solved and some other errors occured. How can I solve this issue?
const showOptions = () => {
let faculties = [];
facultiesService.getAllFaculties()
.then(async (resp) => {
faculties = await resp.data;
})
.catch(e => console.log(e));
console.log(faculties)
return faculties.map(faculty => {
return <option
key={faculty.id}
value={faculty.id}
>{faculty.name}
</option>
});
}
const showFacultySelect = () => {
return (
<Form.Select aria-label="Default select example">
{showOptions()}
</Form.Select>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在以错误的方式使用异步/等待。它们是用于顺序代码而不是回调的。您应该做这样的事情:
You are using async/await in wrong way. They are meant for sequential code rather than callbacks. You should be doing something like this: