首先,我认为您应该将您的Graph数据保存到您的状态中,然后在您的useEffect
钩子中,您可以调用setFsm
重新渲染您的Graph。
您也可以部分更新您的图表数据,但在以下示例中,我将仅替换为您的新图表数据。
你也应该叫clearTimeout
你useEffect
回传功能,以防止内存泄漏在您的应用程序(以防万一组件之前卸除setFsm
的叫法)
我在上一个答案中意识到的一件事是,每次fsm
更新时,它都会setTimeout
再次调用,从而导致fsm
更新,从而导致另一个setTimeout
,本质上就像一个无限循环。我已经更新了我的答案,以便setTimeout
仅调用onMount
,而另一个useEffect
仅用于渲染/更新图形。我认为这样的代码更有意义。
您可以使用此代码作为参考。
function App() {
const [fsm, setFsm] = useState({
init: "open",
transitions: [
{ name: "clodsdse", from: "open", to: "closed" },
{ name: "open", from: "closed", to: "open" },
{ name: "openss", from: "closed", to: "open" },
{ name: "ss", from: "a", to: "b" }
]
});
const renderGraph = () => {
d3.select("#graph").graphviz().renderDot(visualize(new StateMachine(fsm)));
};
// for graph rendering after each update
useEffect(renderGraph, [fsm]);
// only setTimeout onMount and clearTimeout willUnmount
useEffect(() => {
const timer = setTimeout(() => {
setFsm({
init: "open",
transitions: [
{ name: "clodsdse", from: "open", to: "closed" },
{ name: "open", from: "closed", to: "open" },
{ name: "openss", from: "closed", to: "open" },
{ name: "ss", from: "a", to: "b" },
{ name: "sasdss", from: "a", to: "bb" }
]
});
}, 2000);
return () => {
clearTimeout(timer);
};
}, []);
return (
<div className="App">
<div id="graph" />
</div>
);
}