zustand-store-ts
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseZustand Store
Zustand Store
Create Zustand stores following established patterns with proper TypeScript types and middleware.
遵循既定模式创建Zustand store,搭配规范的TypeScript类型与中间件。
Quick Start
快速开始
Copy the template from assets/template.ts and replace placeholders:
- → PascalCase store name (e.g.,
{{StoreName}})Project - → Brief description for JSDoc
{{description}}
从assets/template.ts复制模板并替换占位符:
- → 大驼峰式(PascalCase)的store名称(例如:
{{StoreName}})Project - → JSDoc的简短描述
{{description}}
Always Use subscribeWithSelector
务必使用subscribeWithSelector
typescript
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
export const useMyStore = create<MyStore>()(
subscribeWithSelector((set, get) => ({
// state and actions
}))
);typescript
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
export const useMyStore = create<MyStore>()(
subscribeWithSelector((set, get) => ({
// state and actions
}))
);Separate State and Actions
分离状态与操作
typescript
export interface MyState {
items: Item[];
isLoading: boolean;
}
export interface MyActions {
addItem: (item: Item) => void;
loadItems: () => Promise<void>;
}
export type MyStore = MyState & MyActions;typescript
export interface MyState {
items: Item[];
isLoading: boolean;
}
export interface MyActions {
addItem: (item: Item) => void;
loadItems: () => Promise<void>;
}
export type MyStore = MyState & MyActions;Use Individual Selectors
使用独立选择器
typescript
// Good - only re-renders when `items` changes
const items = useMyStore((state) => state.items);
// Avoid - re-renders on any state change
const { items, isLoading } = useMyStore();typescript
// 推荐 - 仅当`items`变化时重新渲染
const items = useMyStore((state) => state.items);
// 避免 - 任何状态变化都会触发重新渲染
const { items, isLoading } = useMyStore();Subscribe Outside React
在React外部订阅
typescript
useMyStore.subscribe(
(state) => state.selectedId,
(selectedId) => console.log('Selected:', selectedId)
);typescript
useMyStore.subscribe(
(state) => state.selectedId,
(selectedId) => console.log('Selected:', selectedId)
);Integration Steps
集成步骤
- Create store in
src/frontend/src/store/ - Export from
src/frontend/src/store/index.ts - Add tests in
src/frontend/src/store/*.test.ts
- 在目录下创建store
src/frontend/src/store/ - 从导出
src/frontend/src/store/index.ts - 在中添加测试
src/frontend/src/store/*.test.ts