[英]Unable to fetch html content in vercel server using React
我正在使用 Reactjs 并使用 nextjs 框架,HTML 内容(description_front)在 localhost 中显示数据正常这是 api 响应(控制台)
Object
id: "55"
description_front: "<h3><strong>The crypto revolution and its effects</strong></h3>"
但是每当我尝试通过 api 在服务器(vercel)中显示“html”内容时,我都会在控制台中获取以下数据,但是每当我尝试在网页中显示“description_front”时,我都会收到以下错误
Cannot read properties of undefined (reading 'description_front')
这是我的代码,我错在哪里?
import Axios from "axios";
import {useRouter} from "next/router";
const Post = ({ post }) => {
const router = useRouter();
const htmlString = post.description_front;
return (
<>
<div className="product-des" dangerouslySetInnerHTML={{ __html: htmlString }} />
<>
);
};
从 localhost 获取数据时,获取速度可能非常快,这意味着甚至在页面渲染完成之前就会获取数据,并且原始代码将按预期工作。
但是从远程服务器获取时,需要更多时间,所以渲染过程会在获取数据之前完成,并且post.description_front
将为空,是什么导致了这个错误。
解决方案是在渲染之前检查该值是否为空,因此一个衬里将是: const htmlString = post?.description_front
而不是const htmlString = post.description_front
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.