參考鉤子

useStoreApi

在 GitHub 上查看原始碼

在某些情況下,您可能需要直接存取 store。這個 Hook 會傳回 store 物件,您可以在需要時使用它來存取狀態或發送動作。

只有在沒有其他方法可以存取內部狀態時,才應使用這個 Hook。對於許多常見的使用案例,都有可用的專用 Hook,例如 useReactFlowuseViewport 等。

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 Hook 中的範例不同,後者會在節點數變更時重新渲染元件。

選擇要按需計算值還是訂閱變更以了解它們何時發生是一個需要權衡的過程。一方面,在事件處理常式中放置太多繁重的計算可能會使您的應用程式感覺遲緩或沒有反應。另一方面,過早計算值可能會導致緩慢或不必要的重新渲染。

我們提供這個 Hook 和 useStore,以便您可以選擇最適合您的使用案例的方法。

簽名

#回傳值
Zustand.StoreApi<ReactFlowState>

Typescript

這個 Hook 接受自訂節點和邊緣類型的泛型類型引數。請參閱我們的 Typescript 指南中的這個章節 以取得更多資訊。

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