useStoreApi()
在某些情况下,你可能需要直接访问存储。此钩子返回存储对象,可根据需要用于访问状态或分发操作。
🌐 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.
只有在没有其他方式访问内部状态时,才应使用此钩子。对于许多常见的使用情况,存在专用的钩子可用,如 useReactFlow、useViewport 等。
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.
我们提供这个 hook 和 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.
| Name | Type |
|---|---|
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
这个 hook 接受自定义节点和边类型的通用类型参数。有关更多信息,请参阅我们 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>();