主页

react使用接口调用文章内容的时候,html没有正常处理

2023-10-30 10:08AM

参考:https://stackoverflow.com/questions/27934238/rendering-raw-html-with-reactjs

原代码如下:

// src/article/show.js

port React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import axios from 'axios';
                                             
function ArticleDetail() {
   // 初始化为 null,避免初始渲染时显示空的文章
   const [article, setArticle] = useState(null);
   
   const { id } = useParams();
   // 检查路由参数的值
   console.log(id);
   useEffect(() => {
   const fetchArticle = async () => {
     try {
       const response = await axios.get(`http://your-api-url/articles/${id}`);
       // 检查返回的数据结构                                                                          
       console.log(response.data);
       setArticle(response.data);                                                                     
     } catch (error) {                                                                                
       console.error("请求错误:", error);                                                             
     }
   };
       
    fetchArticle();
  }, [id]); // 将 id 添加到依赖数组中,以便在 id 改变时重新获取文章
           
  return (  
     <div>     
     {/* 添加条件表达式的判断 */}
      {article && (
         <div> 
           <h2>{article.title}</h2>                                                   
           <p>{article.created_at}</p>                                                                
           <p>{article.content }</p>                              
         </div>
       )}
     </div>
   );
 

export default ArticleDetail;

在浏览器打开页面:

 

解决方法:

修改 src/article/show.js 文件的这一行 代码: 

  <p>{article.content }</p>                               

修改为:

<p dangerouslySetInnerHTML={{ __html: article.content }}></p> 

在浏览器打开页面:

 

就可以了

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论