简体   繁体   English

无法使用 React 在 Vercel 服务器中获取 html 内容

[英]Unable to fetch html content in vercel server using React

I am working with Reactjs and using nextjs framework,Html content(description_front) is showing data fine in localhost Here is api response (console)我正在使用 Reactjs 并使用 nextjs 框架,HTML 内容(description_front)在 localhost 中显示数据正常这是 api 响应(控制台)

Object
id: "55"
description_front: "<h3><strong>The crypto revolution and its effects</strong></h3>"

but whenever I am trying to display ,"html" content in server(vercel) via api, i am getting following data in my console,But whenever i am trying to display "description_front" in web page i am getting following error但是每当我尝试通过 api 在服务器(vercel)中显示“html”内容时,我都会在控制台中获取以下数据,但是每当我尝试在网页中显示“description_front”时,我都会收到以下错误

Cannot read properties of undefined (reading 'description_front')

Here is my code, where i am wrong ?这是我的代码,我错在哪里?

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 }} />
    <>
    );
  };

When fetching data from localhost, the fetching is probably very quick, means that the data will be fetched even before the page render will be completed, and the original code will work as supposed.从 localhost 获取数据时,获取速度可能非常快,这意味着甚至在页面渲染完成之前就会获取数据,并且原始代码将按预期工作。

But when fetching from a remote server, it takes more time, so the rendering process will be done before the data is fetched, and post.description_front will be null, what's causing this error.但是从远程服务器获取时,需要更多时间,所以渲染过程会在获取数据之前完成,并且post.description_front将为空,是什么导致了这个错误。

The solution will be to check if the value is null before rendering, so a one liner will be: const htmlString = post?.description_front instead of const htmlString = post.description_front解决方案是在渲染之前检查该值是否为空,因此一个衬里将是: const htmlString = post?.description_front而不是const htmlString = post.description_front

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM