在React中启动另一个调用之前,如何等待一个API调用完成



因此,在我的React应用程序中,我使用fetch API来获取"线程"项的列表,并使用另一个调用来获取"类别"的列表。我的"线程"列表立即被呈现到DOM中,在一个DOM元素中,它取决于"类别"列表的存在。它在大多数情况下都能工作,但偶尔会在填充"类别"之前提取"线程",尝试访问"类别"的DOM元素会抛出错误,说我正在尝试访问未定义元素的属性。在获取"线程"之前,我基本上需要找到一种等待"类别"获取和填充的方法。

useEffect(() => {
getCategories();
getThreads();
}, []);
function getThreads() {
loadThreads(categoryId, Feed.threadPage++, 10)
.then((r) => {
if (r.status === 200) {
r.text().then((responseBody) => {
let responseBodyObject = JSON.parse(responseBody);
if (responseBodyObject.threads.length === 0)
setHasMoreThreads(false);
setThreads(threads.concat(responseBodyObject.threads));
});
} else {
toast.error("Failed to fetch threads");
}
})
.catch((e) => toast.error("Failed to fetch threads."));
}
function getCategories() {
loadCategories()
.then((r) => {
if (r.status === 200) {
r.text().then((responseBody) => {
let responseBodyObject = JSON.parse(responseBody);
setCategories(responseBodyObject.categories);
});
} else {
toast.error("Failed to load the categories");
}
})
.catch((e) => toast.error("Failed to load the categories"));
}

在我的DOM中,我得到了:

{threads.map((v, i) => (
<div key={i}>
<div
className={classes.feedThreadBox}
onClick={(e) => console.log(v)}
>
<h5 style={{ marginBottom: 0 }}>
{v != undefined && v.title}
</h5>
<i
className="fa fa-circle fa-xs"
style={{
color:
"#" +
categories.find(
(category) => category.id === v.categoryId
).color,
fontSize: 10,
}}
></i>{" "}
{
categories.find(
(category) => category.id === v.categoryId
).name
}
</div>
<hr></hr>
</div>
))}

如何确保在"threads.map"渲染之前填充"categories"?

您应该使用async/await:

  • 将async关键字放在getCategories((函数前面

  • 在函数的主体中使用等待

你可以在这里找到更多的使用信息

最新更新