Angular集成ReactFlow后图表更新不重新渲染问题排查
问题分析与解决方案
核心问题1:ReactFlow绑定的是初始计算值而非状态变量
你的ReactFlow组件渲染时绑定的是初始化阶段计算的layoutedNodes和layoutedEdges,而非通过useNodesState/useEdgesState维护的响应式状态变量nodes和edges。这导致即使setNodes/setEdges更新了状态,组件也不会渲染最新的节点与边数据。
核心问题2:useCallback依赖项错误
onLayout的依赖数组中声明了nodes和edges,但实际需要依赖的是父组件传入的propNodes和propEdges——错误的依赖会导致回调捕获旧的props值,或不必要地重复创建回调函数。
修复后的React组件代码
export const CustomReactComponent: React.FunctionComponent<AppProps> = ({propNodes, propEdges}: AppProps) => { // 初始化时计算默认布局 const initialLayout = getLayoutedElements(propNodes, propEdges, 'LR'); const [nodes, setNodes, onNodesChange] = useNodesState(initialLayout.nodes); const [edges, setEdges, onEdgesChange] = useEdgesState(initialLayout.edges); const onLayout = useCallback( (direction) => { const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements( propNodes, propEdges, direction ); setNodes([...layoutedNodes]); setEdges([...layoutedEdges]); }, // 依赖父组件传入的props,而非本地状态 [propNodes, propEdges] ); return ( <> <div className="layoutflow"> <ReactFlow {/* 绑定响应式状态变量 */} nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={onConnect} connectionLineType={ConnectionLineType.SmoothStep} style={{ height: 500 }} nodesDraggable={true} fitView /> <div className="controls"> <button className="w3-button w3-green w3-left-align commonFont" onClick={() => onLayout('TB')}>vertical layout</button> <button className="w3-button w3-green w3-left-align commonFont" onClick={() => onLayout('LR')}>horizontal layout</button> </div> </div> </> ); };
额外注意(Angular侧)
确保当this.graph数据更新时,会重新调用render方法。如果仅在初始化阶段调用一次render,Angular侧的graph变化无法传递给React组件。可以在graph的setter方法或ngOnChanges钩子中触发render。
内容的提问来源于stack exchange,提问作者leolove
相关产品推荐
相关产品推荐

