首页 > 解决方案 > React - 'react-d3-graph' 不呈现图表组件

问题描述

我以“react-d3-graph”为例:

https://codesandbox.io/s/long-wood-7evr8?fontsize=14&hidenavigation=1&theme=dark&file=/src/App.js:138-417

我正在尝试通过使用 fetch 从文件中读取数据来渲染“react-d3-graph”中的 Graph 组件来处理非硬编码数据。

但是,当我通过 fetch() 从文件中读取数据并将从文件中读取的数据分配给组件时,我会在控制台中收到这些消息,但什么也没有显示。

react-d3-graph :: Graph :您没有为 react-d3-graph 提供足够的数据来渲染某些东西。您需要提供至少一个节点

react-d3-graph :: Graph :: 您将无效数据传递给 react-d3-graph。您必须在传递给组件的数据对象中包含一个链接数组,即使是空的。

此消息显示在从文件读取的数据的控制台输出之前,因此这是一个时间问题。我试过四处阅读,但找不到解决方法。

任何人都可以请帮忙。谢谢。

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

class GraphView extends Component {


constructor(props) {
    super(props)
    this.state = {
        data : {}
    }
}

componentDidMount() {
    fetch("http://10.10.1.185:4200/chartdata.txt")

        .then((r) => r.text())
        .then(text => {
            console.log("text=" + text);
            this.state.data = text
            console.log("this.state.data=" + this.state.data)
        })
}

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) {
        const clickedNode = { nodeId };
        window.alert(`onRightClickNode link  ${event} and ${nodeId}`);
    };
    
    return (
        <div>
            
            <Graph
                id="graph-id" 
                data={this.state.data}
                config={myConfig}
                onClickNode={onClickNode}
                onClickLink={onClickLink}
                onRightClickNode={onRightClickNode}                

            />;
        </div>
    );
}
}

export default GraphView

标签: javascriptreactjsd3.js

解决方案


因为您是直接操作状态而不是使用setState. 在反应中,您绝不能直接操纵状态。所以改变

.then(text => {
     console.log("text=" + text);
     this.state.data = text
     console.log("this.state.data=" + this.state.data)
 })

至:

.then(text => {
     console.log("text=" + text);
     this.setState({data: text})
     console.log("this.state.data=" + this.state.data)
 })

推荐阅读