乐闻世界logo
搜索文章和话题

如何使用 Zustand 创建和管理全局状态?

3月6日 21:41

Zustand 状态管理的基本步骤:

  1. 安装 Zustand

    bash
    npm install zustand # 或 yarn add zustand
  2. 创建 Store

    javascript
    import { 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 }), }));
  3. 在组件中使用

    javascript
    import { 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> ); }
  4. 选择订阅

    • 只订阅需要的状态部分,避免不必要的重渲染
    • 使用回调函数选择状态的特定属性
  5. 状态更新

    • 使用 set 函数更新状态
    • 支持函数式更新(接收当前状态并返回新状态)
    • 可以批量更新多个状态

最佳实践:

  • 按功能模块组织多个 store
  • 使用中间件增强功能
  • 合理使用选择订阅优化性能
  • 结合 TypeScript 提高类型安全性
标签:Zustand