Skip to Content
参考钩子

useEdgesState()

GitHub上的源代码 

这个钩子使得原型化一个受控流变得容易,其中你可以在 ReactFlowInstance 外部管理节点和边的状态。你可以把它看作是带有额外辅助回调的 React useState 钩子。

🌐 This hook makes it easy to prototype a controlled flow where you manage the state of nodes and edges outside the ReactFlowInstance. You can think of it like React’s useState hook with an additional helper callback.

import { ReactFlow, useNodesState, useEdgesState } from '@xyflow/react'; const initialNodes = []; const initialEdges = []; export default function () { const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes); const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges); return ( <ReactFlow nodes={nodes} edges={edges} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} /> ); }

签名

🌐 Signature

Parameters:
NameTypeDefault
initialEdgesEdgeType[]
Returns:
[edges: EdgeType[], setEdges: Dispatch<SetStateAction<EdgeType[]>>, onEdgesChange: OnEdgesChange<EdgeType>]
  • edges: The current array of edges. You might pass this directly to the edges prop of your <ReactFlow /> component, or you may want to manipulate it first to perform some layouting, for example.

  • setEdges: A function that you can use to update the edges. You can pass it a new array of edges or a callback that receives the current array of edges and returns a new array of edges. This is the same as the second element of the tuple returned by React’s useState hook.

  • onEdgesChange: A handy callback that can take an array of EdgeChanges and update the edges state accordingly. You’ll typically pass this directly to the onEdgesChange prop of your <ReactFlow /> component.

TypeScript

这个钩子接受自定义边类型的泛型类型参数。有关更多信息,请参见我们 TypeScript 指南中的这一部分

🌐 This hook accepts a generic type argument of custom edge types. See this section in our TypeScript guide for more information.

const nodes = useEdgesState<CustomEdgeType>();

注释

🌐 Notes

  • 创建这个 hook 是为了让原型设计更容易,并让我们的文档示例更清晰。虽然在生产环境中使用这个 hook 是可以的,但实际上你可能希望使用像 Zustand 这样更复杂的状态管理解决方案。
Last updated on