前端开发
在 json-render 中用 Zustand…
适用于 json-render + Zustand 集成,让 json-render 的状态读写走 Zustand,并支持嵌套 slice。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 38/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 60/100 ×0.15
适用场景
在 json-render 中用 Zus特定
解决思路
- 安装依赖:`npm install @json-render/zustand @json-render/core @json-render/react zustand`。
- 确保使用 Zustand v5+;Zustand v4 因 vanilla store 接口存在破坏性 API 变更而不支持。
- 从 `zustand/vanilla` 导入 `createStore`,创建 Zustand vanilla store,例如 `const bearStore = createStore(() => ({ count: 0, name: "Bear" }));`。
- 从 `@json-render/zustand` 导入 `zustandStateStore`,调用 `zustandStateStore({ store: bearStore })` 创建 json-render 的 `StateStore` 适配器。
- 从 `@json-render/react` 导入 `StateProvider`,用 `<StateProvider store={store}>...</StateProvider>` 包裹组件;json-render 的读写会经过 Zustand。
- 当状态位于嵌套 slice 时,创建包含嵌套对象如 `ui`、`auth` 的 Zustand store。
- 在 `zustandStateStore` 中传入 `selector` 选择 json-render 使用的 slice,例如 `selector: (s) => s.ui`。
- 同时传入 `updater` 将 next state 写回对应 slice,例如 `updater: (next, s) => s.setState({ ui: next })`。
- 调用 API `zustandStateStore(options)`:创建由 Zustand store 支撑的 `StateStore`。
- Option `store`:类型 `StoreApi<S>`,必填,传入来自 `zustand/vanilla` 的 `createStore` 创建的 Zustand vanilla store。
- Option `selector`:类型 `(state) => StateModel`,可选,用于选择 json-render slice;默认使用整个 state。
- Option `updater`:类型 `(nextState, store) => void`,可选,用于把 next state 应用到 store;默认浅合并;嵌套 slice 需要覆盖;如需完整替换可使用 `(next, s) => s.setState(next, true)`。
适用边界 · 注意事项
- Zustand v4 不支持,因为 vanilla store 接口有破坏性 API 变更。
- 未使用 json-render 的 `StateProvider` / `StateStore` 时不需要此适配器。
- 状态管理不使用 Zustand 时不应使用此适配器。