关于 zustand-store-ts
zustand-store-ts 是用于创建 Zustand 状态存储的技能,涵盖 TypeScript 类型和中间件模式。它提供选择器订阅、状态与操作拆分、React 选择器及测试方面的指导。
主要功能
- 01为状态和操作定义类型
- 02基于选择器的订阅
- 03使用独立 React 选择器
- 04在 React 外订阅状态
- 05组织存储导出与测试
适用场景
- 01创建带类型的 Zustand 存储
- 02减少不必要的 React 重渲染
- 03在 React 外响应选定状态变化
- 04组织存储导出和测试
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill zustand-store-ts安装后在 Claude Code 中输入/zustand-store-ts确认已加载。
详细介绍
Zustand Store
遵循既定模式创建 Zustand store,并使用恰当的 TypeScript 类型和中间件。
快速开始
此处未附带 assets/template.ts。请根据已安装的 Zustand 版本和项目中的实际类型调整内联示例;这些只是代码片段,并非完整应用。
使用 subscribeWithSelector 订阅选择器
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
export const useMyStore = create<MyStore>()(
subscribeWithSelector((set, get) => ({
// state and actions
}))
);
分离状态和操作
export interface MyState {
items: Item[];
isLoading: boolean;
}
export interface MyActions {
addItem: (item: Item) => void;
loadItems: () => Promise<void>;
}
export type MyStore = MyState & MyActions;
使用单独的选择器
// Good - only re-renders when `items` changes
const items = useMyStore((state) => state.items);
// Avoid - re-renders on any state change
const { items, isLoading } = useMyStore();
在 React 外部订阅
useMyStore.subscribe(
(state) => state.selectedId,
(selectedId) => console.log('Selected:', selectedId)
);
集成步骤
- 在
src/frontend/src/store/中创建 store - 从
src/frontend/src/store/index.ts导出 - 在
src/frontend/src/store/*.test.ts中添加测试
适用场景
当任务明确符合上述概述所述的工作流或操作时,可使用此技能。
限制
- 仅当任务明确符合上述范围时使用此技能。
- 请勿将输出视为针对特定环境进行验证、测试或专家审查的替代品。
- 如果缺少必要的输入、权限、安全边界或成功标准,请停止并要求澄清。
评论
支持 Markdown