You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React对接Laravel API获取HTML数据渲染异常求助

Hey there! Let's break down what's going on here and fix that frustrating HTML rendering issue.

First, Let's Diagnose the Root Cause

The most common culprits here are either:

  1. Your Laravel API is returning a full HTML page (like a view or error page) instead of the expected HTML fragments/JSON data
  2. You're not using the HTML parser correctly in your React component

Step 1: Verify Your Laravel Controller Output

First, check if your API is returning the right data. Open your browser's DevTools, go to the Network tab, and make the upcomingdues request. Look at the response content:

  • If it's a full HTML page (with <html>, <head> tags), your controller is returning a view instead of API data. Fix this by updating your controller to return JSON with your HTML content:
    // Example Laravel controller method
    public function getUpcomingDues()
    {
        // Fetch your data and generate HTML fragments
        $dues = // ... your data logic here
        $htmlItems = $dues->map(function($due) {
            return [
                'id' => $due->id,
                'html' => "<div class='due-item'>{$due->title} - {$due->date}</div>"
            ];
        });
    
        // Return JSON instead of a view
        return response()->json($htmlItems);
    }
    
  • If the response is valid JSON with HTML snippets, move to the next step.

Step 2: Fix the React Parser Implementation

You mentioned using html-react-parser and react-render-html but they didn't work. The issue is likely how you're integrating them into your component. Let's use html-react-parser (the maintained option) correctly:

  1. Install the package first:

    npm install html-react-parser --save
    
  2. Update your React component to use the parser properly:

    import React, { Component } from 'react';
    import axios from 'axios';
    import parse from 'html-react-parser'; // Import the parser
    
    export default class Notify extends Component { 
      state={ duelist: [] } 
    
      componentDidMount() { 
        axios.get(`upcomingdues`) 
          .then(res => { 
            this.setState({ duelist: res.data }); 
          })
          .catch(err => {
            console.error('API Request Error:', err); // Add error logging for debugging
          })
      } 
    
      render() { 
        const mystyle = { height: "300px", overflow: "hidden" }; 
        const mystyle1 = { left: "0px", bottom: "0px" }; 
        const mystyle2 = { left: "0px", width: "0px" }; 
    
        return ( 
          <div> 
            <div className="tab-content"> 
              <div className="tab-pane active show" id="topbar_notifications_notifications" role="tabpanel"> 
                <div className="kt-notification kt-margin-t-10 kt-margin-b-10 kt-scroll ps" data-scroll="true" data-height="300" data-mobile-height="200" style={mystyle}> 
                  {/* Loop through your data and parse each HTML snippet */}
                  {this.state.duelist.length > 0 ? (
                    this.state.duelist.map((item) => (
                      <div key={item.id} className="notification-entry">
                        {parse(item.html)} {/* Parse the HTML string into React elements */}
                      </div>
                    ))
                  ) : (
                    <p>No upcoming dues to display</p>
                  )}
                </div> 
              </div> 
            </div> 
            <div className="ps__rail-x" style={mystyle1}> 
              <div className="ps__thumb-x" tabindex="0" style={mystyle2}></div> 
            </div> 
          </div> 
        ); 
      } 
    } 
    
    if (document.getElementById('notify')) { 
      ReactDOM.render(<Notify />, document.getElementById('notify')); 
    }
    

Key Notes to Remember

  • Never render raw HTML strings directly: React automatically escapes raw HTML to prevent XSS attacks, so you must use a parser to convert the string into valid React elements.
  • Debug your API response: Always check the Network tab to confirm what data your React app is actually receiving. If it's a full HTML page, fix your Laravel route/controller first.
  • Add error handling: The catch block in the Axios request will help you spot issues like 404 errors or invalid JSON responses.

内容的提问来源于stack exchange,提问作者wontone_boys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:14:28