Skip to Content

ReactFlowProvider

如果你在页面上使用多个流程,或者使用客户端路由,你需要用 ReactFlowProvider 封装每个流程,以便每个流程都有自己的 store 实例。如果你想在 ReactFlow 组件外部访问内部状态,使用 ReactFlowProvider 也是必需的。

🌐 If you are working with multiple flows on a page or if you are using a client side router you need to wrap each flow with a ReactFlowProvider so that every flow has its own store instance. Using a ReactFlowProvider is also mandatory if you want to access the internal state outside of the ReactFlow component.

import React, { useCallback } from 'react'; import { Background, ReactFlow, ReactFlowProvider, useNodesState, useEdgesState, addEdge, Controls, } from '@xyflow/react'; import Sidebar from './Sidebar'; import '@xyflow/react/dist/style.css'; const initialNodes = [ { id: 'provider-1', type: 'input', data: { label: 'Node 1' }, position: { x: 250, y: 5 }, }, { id: 'provider-2', data: { label: 'Node 2' }, position: { x: 100, y: 100 } }, { id: 'provider-3', data: { label: 'Node 3' }, position: { x: 400, y: 100 } }, { id: 'provider-4', data: { label: 'Node 4' }, position: { x: 400, y: 200 } }, ]; const initialEdges = [ { id: 'provider-e1-2', source: 'provider-1', target: 'provider-2', animated: true, }, { id: 'provider-e1-3', source: 'provider-1', target: 'provider-3' }, ]; const ProviderFlow = () => { const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes); const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges); const onConnect = useCallback( (params) => setEdges((els) => addEdge(params, els)), [], ); return ( <div className="providerflow"> <ReactFlowProvider> <div className="reactflow-wrapper"> <ReactFlow nodes={nodes} edges={edges} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={onConnect} fitView > <Controls /> <Background /> </ReactFlow> </div> <Sidebar nodes={nodes} setNodes={setNodes} /> </ReactFlowProvider> </div> ); }; export default ProviderFlow;
Last updated on