[ PROMPT_NODE_28054 ]
zustand-store-ts
[ SKILL_DOCUMENTATION ]
# Zustand 存储
使用 TypeScript 类型和中间件,按照既定模式创建 Zustand 存储。
## 快速开始
从 assets/template.ts 复制模板并替换占位符:
- `{{StoreName}}` → PascalCase 格式的存储名称(例如 `Project`)
- `{{description}}` → 用于 JSDoc 的简短描述
## 始终使用 subscribeWithSelector
typescript
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
export const useMyStore = create()(
subscribeWithSelector((set, get) => ({
// 状态和操作
}))
);
## 分离状态与操作
typescript
export interface MyState {
items: Item[];
isLoading: boolean;
}
export interface MyActions {
addItem: (item: Item) => void;
loadItems: () => Promise;
}
export type MyStore = MyState & MyActions;
## 使用独立的选择器
typescript
// 推荐 - 仅在 `items` 变化时重新渲染
const items = useMyStore((state) => state.items);
// 避免 - 在任何状态变化时都会重新渲染
const { items, isLoading } = useMyStore();
## 在 React 外部订阅
typescript
useMyStore.subscribe(
(state) => state.selectedId,
(selectedId) => console.log('Selected:', selectedId)
);
## 集成步骤
1. 在 `src/frontend/src/store/` 中创建存储
2. 从 `src/frontend/src/store/index.ts` 导出
3. 在 `src/frontend/src/store/*.test.ts` 中添加测试
## 何时使用
此技能适用于执行概述中描述的工作流或操作。