首页  >  文章  >  web前端  >  State 源代码中的 Set() 用法。

State 源代码中的 Set() 用法。

WBOY
WBOY原创
2024-09-06 06:31:10903浏览

在本文中,我们将了解 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn