Skip to Content
参考手册钩子

useStoreApi()

GitHub 上的源代码

¥Source on GitHub

在某些情况下,你可能需要直接访问存储。此钩子返回存储对象,可根据需要使用该对象来访问状态或分派操作。

¥In some cases, you might need to access the store directly. This hook returns the store object which can be used on demand to access the state or dispatch actions.

Note

仅当没有其他方法访问内部状态时才应使用此钩子。对于许多常见用例,都有专用的钩子可用,例如 useReactFlowuseViewport 等。

¥This hook should only be used if there is no other way to access the internal state. For many of the common use cases, there are dedicated hooks available such as useReactFlow, useViewport, etc.

import { useState, useCallback } from 'react'; import { ReactFlow, useStoreApi } from '@xyflow/react'; const NodesLengthDisplay = () => { const [nodesLength, setNodesLength] = useState(0); const store = useStoreApi(); const onClick = useCallback(() => { const { nodes } = store.getState(); const length = nodes.length || 0; setNodesLength(length); }, [store]); return ( <div> <p>The current number of nodes is: {nodesLength}</p> <button onClick={onClick}>Update node length.</button> </div> ); }; function Flow() { return ( <ReactFlow nodes={nodes}> <NodesLengthLogger /> </ReactFlow> ); }

此示例按需计算流中的节点数。这与 useStore 钩子中的示例形成对比,该示例在节点数发生变化时重新渲染组件。

¥This example computes the number of nodes in the flow on-demand. This is in contrast to the example in the useStore hook that re-renders the component whenever the number of nodes changes.

选择是按需计算值还是订阅更改发生时的变化有点平衡。一方面,在事件处理程序中放入太多繁重的计算会使你的应用感觉迟缓或无响应。另一方面,预计算值可能会导致缓慢或不必要的重新渲染。

¥Choosing whether to calculate values on-demand or to subscribe to changes as they happen is a bit of a balancing act. On the one hand, putting too many heavy calculations in an event handler can make your app feel sluggish or unresponsive. On the other hand, computing values eagerly can lead to slow or unnecessary re-renders.

我们同时提供此钩子和 useStore,以便你可以选择最适合你用例的方法。

¥We make both this hook and useStore available so that you can choose the approach that works best for your use-case.

签名

¥Signature

Parameters:

This function does not accept any parameters.

Returns:

The store object.

NameType
getState() => ReactFlowState<NodeType, EdgeType>
setState(partial: ReactFlowState<NodeType, EdgeType> | Partial<ReactFlowState<NodeType, EdgeType>> | ((state: ReactFlowState<...>) => ReactFlowState<...> | Partial<...>), replace?: boolean | undefined) => void
subscribe(listener: (state: ReactFlowState<NodeType, EdgeType>, prevState: ReactFlowState<NodeType, EdgeType>) => void) => () => void

TypeScript

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

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

const store = useStoreApi<CustomNodeType, CustomEdgeType>();
Last updated on