@xstate/store
XState Store 是一个用于在 JavaScript/TypeScript 应用程序中进行简单状态管理的小型库。它旨在通过 事件 更新存储数据,适用于纯 JavaScript/TypeScript 应用程序、React 应用程序等。它类似于 Zustand、Redux 和 Pinia 等库。对于更复杂的状态管理,您应该使用 XState,或者您可以 将 XState Store 与 XState 一起使用。
安装
- npm
- pnpm
- yarn
npm install @xstate/store
pnpm install @xstate/store
yarn add @xstate/store
快速开始
import { createStore } from '@xstate/store';
const store = createStore({
// 初始上下文
context: { count: 0, name: 'David' },
// 转换
on: {
inc: {
count: (context) => context.count + 1,
},
add: {
count: (context, event: { num: number }) => context.count + event.num,
},
changeName: {
name: (context, event: { newName: string }) => event.newName,
},
},
});
// 获取当前状态(快照)
console.log(store.getSnapshot());
// => {
// status: 'active',
// context: { count: 0, name: 'David' }
// }
// 订阅快照变化
store.subscribe((snapshot) => {
console.log(snapshot.context);
});
// 发送事件
store.send({ type: 'inc' });
// 输出 { count: 1, name: 'David' }
store.send({ type: 'add', num: 10 });
// 输出 { count: 11, name: 'David' }
store.send({ type: 'changeName', newName: 'Jenny' });
// 输出 { count: 11, name: 'Jenny' }
创建一个 store
要创建一个 store,您需要将一个对象传递给 createStore(…)
函数,该对象具有以下属性:
- 初始
context
- 一个
on
对象用于转换(事件处理程序),其中:
- 键是事件类型(例如
"inc"
、"add"
、"changeName"