首頁 > web前端 > js教程 > 主體

State 原始碼中的 Set() 用法。

WBOY
發布: 2024-09-06 06:31:10
原創
902 人瀏覽過

在本文中,我們將了解 Zustand 原始碼中如何使用 Set() 方法。

Set() usage in Zustand’s source code.

所以 Zustand 中的聽眾基本上就是一個 Set。上面的程式碼片段摘自 vanilla.ts

設定

Set 物件可讓您儲存任何類型的唯一值,無論是原始值還是物件參考。集合物件是值的集合。集合中的值只能出現一次;它在該系列的收藏中是獨一無二的。您可以按插入順序迭代集合的元素。 — MDN 文檔

const mySet1 = new Set();

mySet1.add(1); // Set(1) { 1 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add("some text"); // Set(3) { 1, 5, 'some text' }

for (const item of mySet1) {
  console.log(item);
}
// 1, 5, 'some text'
登入後複製

在 Zustand 的 subscribe 函數中加入監聽器。讓我們仔細看看訂閱

訂閱

React專案中如何使用subscribe?以下解釋摘自 Zustand 的自述文件。

訂閱功能允許元件綁定到狀態部分,而無需在變更時強制重新渲染。最好將其與 useEffect 結合起來,以便在卸載時自動取消訂閱。當您被允許直接改變視圖時,這可能會對效能產生巨大的影響。

const useScratchStore = create((set) => ({ scratches: 0, ... }))
const Component = () => {
  // Fetch initial state
  const scratchRef = useRef(useScratchStore.getState().scratches)
  // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
  useEffect(() => useScratchStore.subscribe(
    state => (scratchRef.current = state.scratches)
  ), [])
  ...
登入後複製

現在讓我們來看看 Zustand 中的訂閱原始碼。

const subscribe: StoreApi<TState>['subscribe'] = (listener) => {
    listeners.add(listener)
    // Unsubscribe
    return () => listeners.delete(listener)
}
登入後複製

subscribe 只是將監聽器加入到監聽器集合中。

讓我們看看實驗日誌怎麼說。為了新增 console.log 語句,我使用指令 pnpm run build 編譯了 Zustand,並將 dist 複製到 Examples/demo/src 中。看起來很老套,但嘿,我們正在試驗並弄清楚 Zustand 的內部工作原理。

Set() usage in Zustand’s source code.

Set() usage in Zustand’s source code.

這就是監聽器集的樣子

Set() usage in Zustand’s source code.

我訂閱了 App.jsx 中的更改

// Subscribe to changes in the state
useStore.subscribe((state) => {
  console.log("State changed: ", state);
});
登入後複製

另一個觀察結果是,有一個額外的偵聽器加入此集合:

ƒ () {
  if (checkIfSnapshotChanged(inst)) {
    forceStoreRerender(fiber);
  }
}
登入後複製

關於我們:

在 Think Throo,我們的使命是教授受開源專案啟發的最佳實踐。

透過在 Next.js/React 中練習高階架構概念,將您的編碼技能提高 10 倍,學習最佳實踐並建立生產級專案。

我們是開源的 — https://github.com/thinkthroo/thinkthroo (請給我們一顆星!)

想要為您的企業建立客製化網路系統?請透過 hello@thinkthroo.com 與我們聯絡

作者簡介:

嘿,我是拉姆。我是一名充滿熱情的軟體工程師/OSS Tinkerer。

看我的網站:https://www.ramunarasinga.com/

參考資料:

  1. https://github.com/pmndrs/zustand/blob/main/src/vanilla.ts#L62

  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

  3. https://github.com/pmndrs/zustand/tree/main?tab=readme-ov-file#transient-updates-for-often-occurring-state-changes

以上是State 原始碼中的 Set() 用法。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!