[英]React not outputting axios catch errors on bad API call, getting JavaScript errors instead
当我向我的 API 发出不应该返回任何内容的错误请求时,它会使我的应用程序崩溃,但不会控制台记录我为 axios 设置的任何错误消息,而是收到一堆关于我使用的地图的错误我的组件之一。 我似乎无法找到错误的原因。
带有地图的组件:
const Viewer=({poem})=>{
return(
<>
{
poem.map((item) => {
let author = item.author
let title = item.title
let lines = item.lines
if (author!= undefined && title!= undefined) {
return(
<>
<div className="viewer">
<div className="author">{author}</div>
<div className="title">{title}</div>
<div className="lines">
{lines.map((line) =>
<div>{line}</div>
)}
</div>
</div>
</>
)
}
})
}
</>
)
}
之后,我的页面变为空白,直到我重新加载它,我收到 3 条错误消息,说poem.map 不是一个函数。
以下是我获取 API 的方式:
const searchPoem= (event) => {
if(event.key==="Enter")
{
axios.get("https://poetrydb.org/"+option+"/"+search+"/all")
.then(res=>setPoemData(res.data))
.catch((err) => {
if (err.response) {
console.log(err.response.data)
console.log(err.response.status)
console.log(err.response.headers)
} else if (err.request) {
console.log(err.request)
} else {
console.log('Error', err.message)
}
})
}
}
结果被放入一个 div 中,该 div 使用我的查看器组件生成一张卡片
尝试在组件中记录变量诗歌。
如果 API 不返回任何内容,则该上下文中将不存在变量poem,因此,poem.map 也不存在。
看看条件渲染 - https://reactjs.org/docs/conditional-rendering.html
您可以在渲染函数中使用类似于下面的内容来处理此问题。
poem && Viewer(poem)
当在非数组变量上调用.map()
时,会抛出错误。
由于在错误的 API 调用后分页中断,防止它的一种方法是在执行poem.map()
Array.isArray()
检查poem
是否是一个数组。
const Viewer = ({ poem }) => {
return (
<>
{Array.isArray(poem) // Add extra type checking before rendering
? (
poem.map((item) => {
let author = item.author;
let title = item.title;
let lines = item.lines;
if (author != undefined && title != undefined) {
return (
<>
<div className="viewer">
<div className="author">{author}</div>
<div className="title">{title}</div>
<div className="lines">
{lines.map((line) => (
<div>{line}</div>
))}
</div>
</div>
</>
);
}
})
)
: null // or a error message component
}
</>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.