javascript - React - 'react-d3-graph' 不呈现图表组件
问题描述
我以“react-d3-graph”为例:
我正在尝试通过使用 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
解决方案
因为您是直接操作状态而不是使用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)
})
推荐阅读
- python - 我是python编程的初学者。我不断收到 typeError: object() 没有参数,我不知道如何解决它。我应该怎么办?
- flutter - 如何在 Flutter 的 AlertDialog 上设置背景图像?
- java - 使用 OpenCSV 库会引发运行时异常 ListValuedMap 'Class not found'
- python - 如何使用 python 将终端输出打印到网格中的 tkinter 帧?
- ios - 如何根据设备屏幕调整 UICollectionViewCell 的大小
- java - 浮动变量 beign 更改而没有明确地归属
- c++ - C++ Karatsuba 长整数算法错误
- javascript - 如何要求用户提供通知以启用更好的可见方式?
- spring-boot - 不使用jwt如何实现资源服务器
- c++ - 使用外部库的问题 (GEGELATI)