Skip to Content
参考手册钩子

useNodesState()

GitHub 上的源代码

¥Source on 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
initialNodesNodeType[]
Returns:
[nodes: NodeType[], setNodes: Dispatch<SetStateAction<NodeType[]>>, onNodesChange: OnNodesChange<NodeType>]
  • nodes: The current array of nodes. You might pass this directly to the nodes prop of your <ReactFlow /> component, or you may want to manipulate it first to perform some layouting, for example.
  • setNodes: A function that you can use to update the nodes. You can pass it a new array of nodes or a callback that receives the current array of nodes and returns a new array of nodes. This is the same as the second element of the tuple returned by React’s useState hook.
  • onNodesChange: A handy callback that can take an array of NodeChanges and update the nodes state accordingly. You’ll typically pass this directly to the onNodesChange prop of your <ReactFlow /> component.

TypeScript

此钩子接受自定义节点类型的泛型类型参数。有关更多信息,请参阅此 我们 TypeScript 指南中的部分

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

const nodes = useNodesState<CustomNodeType>();

注释

¥Notes

  • 创建此钩子是为了使原型设计更容易,使我们的文档示例更清晰。虽然在生产中使用这个钩子是可以的,但在实践中,你可能希望使用更复杂的状态管理解决方案,如 Zustand

    ¥This hook was created to make prototyping easier and our documentation examples clearer. Although it is OK to use this hook in production, in practice you may want to use a more sophisticated state management solution like Zustand instead.

Last updated on