为什么当数据获取失败时,vite 会让我的 React 应用程序变成空页面,并且我有元素要在错误时渲染?
我不明白真正的原因,但只有在代码完美的情况下它才有效。
即使源代码中有拼写错误的 HTML 标签,它也会删除所有 UI
API获取失败,空页,,, 使用未定义的变量,空页,,, 使用非数组变量的迭代,空页
甚至导航栏和其他布局也无法渲染,
为什么会出现这种情况?
看
import { Link } from "react-router-dom";
import { useQuery, gql } from "@apollo/client";
const REVIEWS = gql`
query GetReviews{
reviews {
data {
id,
attributes{
title
rating
body
}
}
}
}
`
export default function Homepage() {
const { isLoading, error, data } = useQuery(REVIEWS)
if (isLoading) return <p className="text-center text-orange-600 text-xl">Loading...</p>;
**** if (error) return <p className="text-center text-orange-600 text-xl">Error: {error}</p>;
return (
<div className="w-3/4 mx-auto bg-slate-300 p-5 pt-2 mt-3 rounded-md">
<h5 className="mx-auto font-bold text-5xl text-white px-24 rounded-2xl bg-blue-600 text-center mb-5 w-fit">Reviews</h5>
{data&&data.reviews.data.map(review => (
<div key={review.id} className="max-w-3/4 rounded overflow-hidden shadow-lg bg-slate-600 mb-5">
<p className="text-white bg-pink-600 w-fit p-5 rounded-xl text-3xl mb-2">{review.attributes.rating}</p>
<div className="px-6 py-4">
<div className=" text-white font-bold text-xl mb-2">{review.attributes.title}</div>
<p className="text-white text-base">{review.attributes.body[0].children[0].text.substring(0,400)}...</p>
<Link to={`/details/${review.id}`} className="text-green-500 text-base">Read More</Link>
</div>
</div>
))}
</div>
);
}
如果服务器没有运行,DOM 将不显示任何内容, 但它应该呈现上面标有 **** 的代码
如果未打印
Error {error}
,则可能已成功获取您的数据,但是您访问的方式不正确。
检查浏览器的开发工具 (
Ctrl + Shift + I
) 并检查控制台选项卡中记录的错误。
请检查
data
的格式是否正确,以及以下访问是否不会导致任何 undefined
访问:
data.reviews.data
review.attributes.rating
review.attributes.title
review.attributes.body[0]...
data
、reviews
或某些属性可能未定义/缺失。
我现在明白了,我尝试渲染错误对象,并且整个对象不允许通过react渲染。
此错误使我的应用程序出现空白页面
error.message
解决了这个问题
谢谢你