登录
首页 >  文章 >  前端

useSyncExternalStoreExports 状态源码解释

来源:dev.to

时间:2024-09-10 23:33:56 200浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《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 从外部存储读取一个值,该值可以是:

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

  2. 公开可变值和事件以订阅其更改的浏览器 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/extensions
import 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 } = reactexports
const { usesyncexternalstorewithselector } = usesyncexternalstoreexports

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

export function useStoreWithEqualityFn<TState, StateSlice>(
  api: ReadonlyStoreApi<TState>,
  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 联系我们以了解更多信息!

参考资料:

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

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

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

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

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



本篇关于《useSyncExternalStoreExports 状态源码解释》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>