useSyncExternalStoreExports 状态源码解释

在本文中,我们将了解 zustand 如何在其[源代码]中使用 usesyncexternalstoreexports。

useSyncExternalStoreExports 状态源码解释

usesyncexternalstoreexports 是从 use-sync-external-store/shim/with-selector 导入的。 use-sync-external-store 是 react.usesyncexternalstore 的向后兼容垫片,可与任何支持 hooks 的 react 配合使用。

读到上面这句话,你可能想知道什么是usesyncexternalstore。

usesyncexternalstore

usesyncexternalstore 是一个 react hook,可让您订阅外部存储。

const snapshot = usesyncexternalstore(subscribe, getsnapshot, getserversnapshot?)

登录后复制

使用 usesyncexternalstore 从外部存储读取一个值,该值可以是:

在 react 之外保存状态的第三方状态管理库。

公开可变值和事件以订阅其更改的浏览器 api。

用法示例:

import { usesyncexternalstore } from 'react';import { todosstore } from './todostore.js';function todosapp() {  const todos = usesyncexternalstore(todosstore.subscribe, todosstore.getsnapshot);  // ...}

登录后复制

上面的例子摘自react文档。

usesyncexternalstore 在 zustand 中的用法:

zustand 在 src/traditional.ts 中使用 usesyncexternalstore。

import reactexports from 'react'// eslint-disable-next-line import/extensionsimport usesyncexternalstoreexports from 'use-sync-external-store/shim/with-selector'import { createstore } from './vanilla.ts'import type {  mutate,  statecreator,  storeapi,  storemutatoridentifier,} from './vanilla.ts'const { usedebugvalue } = reactexportsconst { usesyncexternalstorewithselector } = usesyncexternalstoreexports

登录后复制

usesyncexternalstorewithselector 是从 usesyncexternalstoreexports 解构而来,并在 usestorewithequalityfn 中使用。

export function useStoreWithEqualityFn(  api: ReadonlyStoreApi,  selector: (state: TState) => StateSlice = identity as any,  equalityFn?: (a: StateSlice, b: StateSlice) => boolean,) {  const slice = useSyncExternalStoreWithSelector(    api.subscribe,    api.getState,    api.getInitialState,    selector,    equalityFn,  )  useDebugValue(slice)  return slice}

登录后复制

usesyncexternalstorewithselector 有 api.subscribe、api.getstate、api.getinitialstate、selector 和 equalfn。

关于我们:

在 think throo,我们的使命是教授受开源项目启发的最佳实践。

通过在 next.js/react 中练习高级架构概念,将您的编码技能提高 10 倍,学习最佳实践并构建生产级项目。

我们是开源的 — https://github.com/thinkthroo/thinkthroo (请给我们一颗星!)

通过我们基于代码库架构的高级课程来提高您的团队的技能。请通过 hello@thinkthroo.com 联系我们以了解更多信息!

参考资料:

https://github.com/pmndrs/zustand/blob/main/src/traditional.ts#l44

https://www.npmjs.com/package/use-sync-external-store

https://legacy.reactjs.org/docs/hooks-reference.html#usesyncexternalstore

https://react.dev/reference/react/usesyncexternalstore

https://github.com/reactwg/react-18/discussions/86

以上就是useSyncExternalStoreExports 状态源码解释的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2669332.html

(0)
上一篇 2025年3月7日 12:43:08
下一篇 2025年3月7日 12:43:16

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论