SuperAPI AI 工具集

zustand

前端与建站

查看项目

更新于 10-16 07:30

技能介绍

@json-render/zustand 是 json-render 的 Zustand 适配器,用于把 Zustand vanilla store 作为 json-render 的状态后端,使 json-render 的读取和写入都经过 Zustand。

主要能力

  • 将 Zustand vanilla store 接入 json-render 的 StateStore 接口。
  • 可通过 selector 选择 json-render 使用的状态切片,默认使用整个 state。
  • 可通过 updater 自定义状态写回方式,默认使用浅合并;嵌套切片可覆写,也可用 (next, s) => s.setState(next, true) 进行完整替换。

安装方式 npm install @json-render/zustand @json-render/core @json-render/react zustand

版本要求 需要 Zustand v5 及以上版本。由于 vanilla store 接口存在破坏性 API 变更,不支持 Zustand v4。

使用方式

  1. 用 zustand/vanilla 的 createStore 创建 Zustand vanilla store。
  2. 用 zustandStateStore 创建 json-render 的 StateStore 适配器。
  3. 在 json-render 中使用该适配器,读写操作会经过 Zustand。

API zustandStateStore(options) 创建一个由 Zustand store 支持的 StateStore。选项包括:

  • store:必填,类型为 StoreApi<S>,即来自 zustand/vanilla 中 createStore 的 Zustand vanilla store。
  • selector:可选,类型为 (state) => StateModel,用于选择 json-render 切片,默认使用整个 state。
  • updater:可选,类型为 (nextState, store) => void,用于将下一状态应用到 store,默认浅合并;嵌套切片需要覆写,或用 (next, s) => s.setState(next, true) 进行完整替换。

嵌套切片示例 const appStore = createStore(() => ({ ui: { count: 0 }, auth: { token: null }, }));

const store = zustandStateStore({ store: appStore, selector: (s) => s.ui, updater: (next, s) => s.setState({ ui: next }), });

适用场景 适用于已经在使用 Zustand v5 管理状态,并希望将 json-render 的 StateStore 读写统一接入现有 Zustand store 的项目;也适用于需要只让 json-render 操作某个嵌套状态切片的场景。

限制 不支持 Zustand v4。默认行为为浅合并,如果目标是嵌套切片或需要替换整体状态,需要显式配置 selector 与 updater。