useStore()
这个钩子可以用来订阅 React Flow 组件的内部状态变化。useStore 钩子是从 Zustand 状态管理库重新导出的,所以你应该查看他们的文档以获取更多细节。
🌐 This hook can be used to subscribe to internal state changes of the React Flow
component. The useStore hook is re-exported from the Zustand
state management library, so you should check out their docs for more details.
这个 Hook 只有在没有其他方法访问内部状态的情况下才应该使用。对于许多常见的使用场景,有专用的 Hook 可用,例如 useReactFlow,useViewport 等。
import { ReactFlow, useStore } from '@xyflow/react';
const nodesLengthSelector = (state) =>
state.nodes.length || 0;
const NodesLengthDisplay = () => {
const nodesLength = useStore(nodesLengthSelector);
return <div>The current number of nodes is: {nodesLength}</div>;
};
function Flow() {
return (
<ReactFlow nodes={[...]}>
<NodesLengthDisplay />
</ReactFlow>
);
}此示例会急切地计算节点数量。每当流中的节点数量发生变化时,<NodesLengthDisplay /> 组件将重新渲染。这与 useStoreApi 钩子中的示例形成对比,后者只有在点击按钮时才计算节点数量。
🌐 This example computes the number of nodes eagerly. Whenever the number of nodes
in the flow changes, the <NodesLengthDisplay /> component will re-render. This
is in contrast to the example in the useStoreApi hook that only
computes the number of nodes when a button is clicked.
选择是按需计算值还是订阅值的变化是一种平衡行为。一方面,将过多的繁重计算放在事件处理程序中可能会让你的应用感觉迟缓或无响应。另一方面,急切地计算值可能会导致渲染变慢或产生不必要的重新渲染。
🌐 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 和 useStoreApi,以便你可以选择最适合你使用场景的方法。
🌐 We make both this hook and useStoreApi available so that you
can choose the approach that works best for your use-case.
签名
🌐 Signature
Parameters:示例
🌐 Examples
触发存储操作
🌐 Triggering store actions
你可以通过触发 useStore 钩子中的内部操作来操作 React Flow 的内部状态。这些操作已经在整个库内部被使用,但你也可以使用它们来实现自定义功能。
🌐 You can manipulate the internal React Flow state by triggering internal actions
through the useStore hook. These actions are already used internally throughout
the library, but you can also use them to implement custom functionality.
import { useStore } from '@xyflow/react';
const setMinZoomSelector = (state) => state.setMinZoom;
function MinZoomSetter() {
const setMinZoom = useStore(setMinZoomSelector);
return <button onClick={() => setMinZoom(6)}>set min zoom</button>;
}TypeScript
这个 Hook 可以通过输入选择器函数来进行类型定义。有关更多信息,请参阅我们 TypeScript 指南中的本节。
🌐 This hook can be typed by typing the selector function. See this section in our TypeScript guide for more information.
const nodes = useStore((s: ReactFlowState<CustomNodeType>) => s.nodes);