Skip to content
 

一、简介

更新: 9/4/2025字数: 0 字 时长: 0 分钟

Zustand 是一个轻量级的 React 状态管理库,相比 Redux 更简单直观,同时提供了强大的功能。小型、快速且可扩展的状态管理解决方案。

Zustand 中文网

二、基本使用

2.1 安装

bash
npm install zustand

2.2 创建 store

可以将任何东西放入其中:原始、对象、函数。set 函数合并状态。

ts
import { create } from "zustand";

interface BearState {
  bears: number;
  increase: () => void;
  decrease: () => void;
  removeBear: () => void;
}

const useBearStore = create<BearState>()((set) => ({
  bears: 0,
  increase: () => set((state) => ({ bears: state.bears + 1 })),
  decrease: () => set((state) => ({ bears: state.bears - 1 })),
  removeBear: () => set({ bears: 0 })
}));

export default useBearStore;

2.3 组件中使用

tsx
import useBearStore from "../../../store/zustand";
function ZustandPage() {
  const bears = useBearStore((state) => state.bears);
  return (
    <div>
      <div>
        <h1>Zustand 正常使用</h1>
        <p>bears: {bears}</p>
        <button onClick={() => useBearStore.getState().increase()}>increase</button> <br></br>
        <button onClick={() => useBearStore.getState().decrease()}>decrease</button>
      </div>
    </div>
  );
}
export default ZustandPage;

解构赋值写法:

tsx
import React from "react";
import useBearStore from "../../../store/zustand";
function ZustandPage() {
  //   使用解构赋值
  const { increase, decrease, bears } = useBearStore();
  return (
    <div>
      <div>
        <h1>Zustand 解构赋值</h1>
        <p>bears: {bears}</p>
        <button onClick={() => increase()}>increase</button> <br></br>
        <button onClick={() => decrease()}>decrease</button>
        <button onClick={() => useBearStore.getState().removeBear()}>removeBear</button>
      </div>
    </div>
  );
}
export default ZustandPage;

三、异步操作

ts
interface FishState {
  fishes: number;
  loading: boolean;
  fetchFishes: () => Promise<void>;
}

const useFishStore = create<FishState>()((set) => ({
  fishes: 0,
  loading: false,
  fetchFishes: async () => {
    set({ loading: true });
    const response = await fetch("/api/fishes");
    const { count } = await response.json();
    set({ fishes: count, loading: false });
  }
}));

四、状态派生

状态派生(Getter)是 Zustand 中一种计算派生状态的模式,它允许你基于 store 中的现有状态计算出新的值,而无需将这些值直接存储在状态中。

4.1 状态派生的作用

  1. 避免冗余存储:不重复存储可以计算得到的数据
  2. 保持状态简洁:只存储原始数据,派生数据实时计算
  3. 响应式更新:当依赖的状态变化时,派生值自动更新
  4. 逻辑封装:将复杂计算逻辑封装在 store 中

基本用法

ts
const useStore = create((set, get) => ({
  count: 0,
  // 派生状态 - 计算count的平方
  get squared() {
    return get().count * get().count;
  },
  // 派生方法 - 也可以定义为函数
  getDouble: () => get().count * 2
}));

4.2 场景示例

1、计算购物车总价

ts
const useCartStore = create((set, get) => ({
  items: [],
  // 派生总价
  get totalPrice() {
    return get().items.reduce((sum, item) => sum + item.price * item.quantity, 0);
  },
  // 派生商品总数
  get itemCount() {
    return get().items.reduce((count, item) => count + item.quantity, 0);
  }
}));

2、 过滤列表数据

ts
const useTodoStore = create((set, get) => ({
  todos: [],
  filter: "all",
  // 派生过滤后的todos
  get filteredTodos() {
    const { todos, filter } = get();
    switch (filter) {
      case "completed":
        return todos.filter((todo) => todo.completed);
      case "active":
        return todos.filter((todo) => !todo.completed);
      default:
        return todos;
    }
  }
}));

我见青山多妩媚,料青山见我应如是。