Zustand 状态管理的基本步骤:
-
安装 Zustand
bashnpm install zustand # 或 yarn add zustand -
创建 Store
javascriptimport { create } from 'zustand'; const useStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), reset: () => set({ count: 0 }), })); -
在组件中使用
javascriptimport { useStore } from './store'; function Counter() { const count = useStore((state) => state.count); const increment = useStore((state) => state.increment); const decrement = useStore((state) => state.decrement); const reset = useStore((state) => state.reset); return ( <div> <h1>Count: {count}</h1> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> <button onClick={reset}>Reset</button> </div> ); } -
选择订阅
- 只订阅需要的状态部分,避免不必要的重渲染
- 使用回调函数选择状态的特定属性
-
状态更新
- 使用
set函数更新状态 - 支持函数式更新(接收当前状态并返回新状态)
- 可以批量更新多个状态
- 使用
最佳实践:
- 按功能模块组织多个 store
- 使用中间件增强功能
- 合理使用选择订阅优化性能
- 结合 TypeScript 提高类型安全性