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

react-d3-graph使用fetch读取文件数据时Graph组件无法渲染如何解决

问题原因及修复方案
  • 问题1:初始状态给了空对象,首次渲染时Graph组件拿到的是没有nodes和links属性的空对象,直接触发报错
  • 问题2:fetch获取到的是文本字符串,没有解析为Graph组件要求的包含nodes、links数组的对象格式
  • 问题3:修改state时直接赋值this.state.data = text,没有调用React的setState方法,不会触发组件重新渲染,Graph组件永远拿不到更新后的数据
  • 问题4:没有做加载态判断,组件初始化就直接渲染Graph,必然先触发报错

修正后完整代码

import React, { Component } from 'react'
import { Graph } from "react-d3-graph";

class GraphView extends Component {
  constructor(props) {
    super(props)
    this.state = {
      // 初始就给符合组件要求的空结构,避免首次渲染报错
      data: {
        nodes: [],
        links: []
      },
      isLoading: true
    }
  }

  componentDidMount() {
    fetch("http://10.10.1.185:4200/chartdata.txt")
      .then((r) => r.json()) // 直接解析为JSON对象,无需转text
      .then(parsedData => {
        console.log("加载到的图数据", parsedData);
        // 用setState更新数据,触发组件重渲染
        this.setState({
          data: parsedData,
          isLoading: false
        })
      })
      .catch(err => {
        console.error("数据加载失败", err)
        this.setState({isLoading: false})
      })
  }

  render() {
    const myConfig = {
      nodeHighlightBehavior: true,
      node: {
        color: "lightgreen",
        size: 200,
        highlightStrokeColor: "blue",
      },
      link: {
        highlightColor: "lightblue",
      },
    };

    const onClickNode = function (nodeId) {
      window.alert(`Clicked node ${nodeId}`);
    };

    const onClickLink = function (source, target) {
      window.alert(`Clicked link between ${source} and ${target}`);
    };

    const onMouseOverNode = function (nodeId, node) {
      window.alert(`Alarms for ${nodeId}  Coords: (${node.x}, ${node.y})`);
    };
    
    const onRightClickNode = function (event, nodeId) {
      window.alert(`onRightClickNode link  ${event} and ${nodeId}`);
    };
    
    // 加载中显示提示,避免空白和报错
    if(this.state.isLoading) {
      return <div>数据加载中...</div>
    }

    return (
      <div>
        <Graph
          id="graph-id" 
          data={this.state.data}
          config={myConfig}
          onClickNode={onClickNode}
          onClickLink={onClickLink}
          onRightClickNode={onRightClickNode}                
        />
      </div>
    );
  }
}

export default GraphView

注意:需要确保chartdata.txt返回的内容是标准JSON格式,结构符合要求的{nodes: [{id: '节点唯一标识'}, ...], links: [{source: '源节点id', target: '目标节点id'}, ...]},如果返回的不是标准JSON,自行处理文本转换为对应结构即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:27:02