【发布时间】:2021-07-02 11:10:46
【问题描述】:
想象一下这样的代码块,我要求在帖子下方显示尚未显示的 cmets(可能有一个加载更多 cmets 的按钮)。
try {
const postId = post._id;
const res = await axios.get(
`${baseUrl}/api/posts/moreComments/${postId}`,
{
params: { yetDisplayedLength },
}
);
const newComments = res.data.comments;
setComments((comments) => [...comments, ...newComments]);
setCommentsLength(res.data.commentsLength);
} catch (error) {
alert(error + "\n Error loading more comments");
}
我的问题是:如果在接收 cmets 时出错,尝试立即中止或继续,然后仍然设置 cmets (setComments((comments) => [...comments, ...newComments]);)?
我问这个是因为在 catch 块中我不知道是否必须像以前那样设置 cmets 状态 (setComments((comments) => comments.pop()))
【问题讨论】:
-
一旦出现错误,代码执行就会停止并跳转到
catch块。例如,如果axios.get()失败,您将不会得到newComments,setComments也不会运行,setCommentsLength也不会运行。从逻辑上讲,它们无法运行,甚至-您如何使 cmets 无中生有?axios.get甚至没有返回null或任何东西,只是出错了。 -
我认为 axios.get 可以处理返回 null 或类似的东西,但在你评论的最后一行你澄清了它。谢谢 VLAZ
标签: javascript reactjs ecmascript-6 try-catch