我正在尝试更新我的图形可视化工具(从基于类的组件切换到功能组件)并且遇到了问题。
当我尝试向图形添加边时,组件不会重新呈现。我尝试了许多不同的方式更新状态,甚至尝试使用 useRef 挂钩但没有成功。我没主意了。有人知道如何解决吗?
我的代码:
function App() {
const [state, setState] = useState({
counter: 5,
graph: {
nodes: [
{ id: 1, label: "Node 1", color: "#e04141" },
{ id: 2, label: "Node 2", color: "#e09c41" },
{ id: 3, label: "Node 3", color: "#e0df41" },
{ id: 4, label: "Node 4", color: "#7be041" },
{ id: 5, label: "Node 5", color: "#41e0c9" }
],
edges: [
{ from: 1, to: 2 },
{ from: 1, to: 3 },
{ from: 2, to: 4 },
{ from: 2, to: 5 }
]
},
events: {
}
})
const stateRef = useRef(state);
const { graph, events } = stateRef.current;
return (
<div>
<Button
onClick={() => {
const temp = {...state};
temp.graph.edges.push({from: 4, to: 5});
console.log(graph);
setState(temp);
}}
>
Add edge
</Button>
<Graph graph={graph} options={options} events={events} style={{ height: "640px" }} />
</div>
);
当我单击“添加边”按钮时,图形组件保持不变。但是,当我查看状态时,边缘就在那里。
非常感谢!