zustand

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

@json-render/zustand

@json-render/zustand

Zustand adapter for json-render's
StateStore
interface. Wire a Zustand vanilla store as the state backend for json-render.
适配json-render的
StateStore
接口的Zustand适配器,可将原生Zustand store作为json-render的状态后端。

Installation

安装

bash
npm install @json-render/zustand @json-render/core @json-render/react zustand
Requires Zustand v5+. Zustand v4 is not supported due to breaking API changes in the vanilla store interface.
bash
npm install @json-render/zustand @json-render/core @json-render/react zustand
需要Zustand v5及以上版本,由于原生store接口存在破坏性API变更,因此不支持Zustand v4。

Usage

使用指南

tsx
import { createStore } from "zustand/vanilla";
import { zustandStateStore } from "@json-render/zustand";
import { StateProvider } from "@json-render/react";

// 1. Create a Zustand vanilla store
const bearStore = createStore(() => ({
  count: 0,
  name: "Bear",
}));

// 2. Create the json-render StateStore adapter
const store = zustandStateStore({ store: bearStore });

// 3. Use it
<StateProvider store={store}>
  {/* json-render reads/writes go through Zustand */}
</StateProvider>
tsx
import { createStore } from "zustand/vanilla";
import { zustandStateStore } from "@json-render/zustand";
import { StateProvider } from "@json-render/react";

// 1. 创建一个原生Zustand store
const bearStore = createStore(() => ({
  count: 0,
  name: "Bear",
}));

// 2. 创建json-render StateStore适配器
const store = zustandStateStore({ store: bearStore });

// 3. 使用该适配器
<StateProvider store={store}>
  {/* json-render的读写操作都将通过Zustand执行 */}
</StateProvider>

With a Nested Slice

搭配嵌套切片使用

tsx
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 }),
});
tsx
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 }),
});

API

API

zustandStateStore(options)

zustandStateStore(options)

Creates a
StateStore
backed by a Zustand store.
OptionTypeRequiredDescription
store
StoreApi<S>
YesZustand vanilla store (from
createStore
in
zustand/vanilla
)
selector
(state) => StateModel
NoSelect the json-render slice. Defaults to entire state.
updater
(nextState, store) => void
NoApply next state to the store. Defaults to shallow merge. Override for nested slices, or use
(next, s) => s.setState(next, true)
for full replacement.
创建由Zustand store驱动的
StateStore
选项类型必填说明
store
StoreApi<S>
原生Zustand store(来自
zustand/vanilla
中的
createStore
方法)
selector
(state) => StateModel
选择json-render对应的状态切片,默认取全部状态
updater
(nextState, store) => void
将新状态应用到store中,默认执行浅合并。使用嵌套切片时可重写该方法,也可通过
(next, s) => s.setState(next, true)
实现全量状态替换。