簡體   English   中英

無法使用 React 在 Vercel 服務器中獲取 html 內容

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM