Zustand 安装与配置 #

安装 Zustand #

Zustand 可以通过多种包管理器安装。

使用 npm #

bash
npm install zustand

使用 yarn #

bash
yarn add zustand

使用 pnpm #

bash
pnpm add zustand

项目配置 #

创建第一个 Store #

安装完成后,创建你的第一个 store:

tsx
// src/stores/counterStore.ts
import { create } from 'zustand'

interface CounterState {
  count: number
  increment: () => void
  decrement: () => void
  reset: () => void
}

export const useCounterStore = create<CounterState>((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
  reset: () => set({ count: 0 }),
}))

在组件中使用 #

tsx
// src/components/Counter.tsx
import { useCounterStore } from '../stores/counterStore'

function Counter() {
  const { count, increment, decrement, reset } = useCounterStore()

  return (
    <div className="counter">
      <h2>计数器: {count}</h2>
      <div className="buttons">
        <button onClick={increment}>增加</button>
        <button onClick={decrement}>减少</button>
        <button onClick={reset}>重置</button>
      </div>
    </div>
  )
}

export default Counter

项目结构建议 #

小型项目结构 #

text
src/
├── components/
│   └── Counter.tsx
├── stores/
│   └── counterStore.ts
├── App.tsx
└── main.tsx

中大型项目结构 #

text
src/
├── components/
│   ├── common/
│   └── features/
│       ├── counter/
│       │   ├── Counter.tsx
│       │   └── CounterControls.tsx
│       └── user/
│           ├── UserProfile.tsx
│           └── UserSettings.tsx
├── stores/
│   ├── index.ts
│   ├── counterStore.ts
│   ├── userStore.ts
│   └── middleware/
│       └── logger.ts
├── types/
│   └── index.ts
├── App.tsx
└── main.tsx

TypeScript 配置 #

Zustand 对 TypeScript 有原生支持,无需额外配置。但建议在 tsconfig.json 中启用严格模式:

json
{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true
  }
}

类型定义示例 #

tsx
// types/store.ts
export interface User {
  id: string
  name: string
  email: string
  avatar?: string
}

export interface UserState {
  user: User | null
  isLoading: boolean
  error: string | null
  login: (email: string, password: string) => Promise<void>
  logout: () => void
  updateUser: (user: Partial<User>) => void
}

// stores/userStore.ts
import { create } from 'zustand'
import type { UserState, User } from '../types/store'

export const useUserStore = create<UserState>((set, get) => ({
  user: null,
  isLoading: false,
  error: null,
  
  login: async (email: string, password: string) => {
    set({ isLoading: true, error: null })
    try {
      const response = await fetch('/api/login', {
        method: 'POST',
        body: JSON.stringify({ email, password }),
      })
      const user = await response.json()
      set({ user, isLoading: false })
    } catch (error) {
      set({ error: '登录失败', isLoading: false })
    }
  },
  
  logout: () => {
    set({ user: null, error: null })
  },
  
  updateUser: (userData: Partial<User>) => {
    const { user } = get()
    if (user) {
      set({ user: { ...user, ...userData } })
    }
  },
}))

开发环境配置 #

ESLint 配置 #

如果你使用 ESLint,可以添加以下规则:

json
{
  "rules": {
    "react-hooks/exhaustive-deps": "warn"
  }
}

VS Code 配置 #

推荐安装以下扩展:

  • ESLint
  • Prettier
  • TypeScript Hero

.vscode/settings.json 中添加:

json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "typescript.preferences.importModuleSpecifier": "relative"
}

与不同框架集成 #

Vite 项目 #

bash
# 创建 Vite 项目
npm create vite@latest my-app -- --template react-ts

# 进入项目目录
cd my-app

# 安装 Zustand
npm install zustand

Next.js 项目 #

bash
# 创建 Next.js 项目
npx create-next-app@latest my-app --typescript

# 安装 Zustand
npm install zustand

Next.js 中使用 Zustand 需要注意 SSR:

tsx
// stores/counterStore.ts
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

interface CounterState {
  count: number
  increment: () => void
}

export const useCounterStore = create<CounterState>()(
  persist(
    (set) => ({
      count: 0,
      increment: () => set((state) => ({ count: state.count + 1 })),
    }),
    {
      name: 'counter-storage',
      storage: createJSONStorage(() => sessionStorage),
    }
  )
)

Create React App #

bash
# 创建 CRA 项目
npx create-react-app my-app --template typescript

# 安装 Zustand
npm install zustand

验证安装 #

创建一个简单的测试组件验证安装是否成功:

tsx
// src/App.tsx
import { create } from 'zustand'

const useTestStore = create((set) => ({
  value: 'Zustand 安装成功!',
  update: (value: string) => set({ value }),
}))

function App() {
  const { value, update } = useTestStore()

  return (
    <div style={{ padding: '20px' }}>
      <h1>{value}</h1>
      <button onClick={() => update('状态更新成功!')}>
        测试更新
      </button>
    </div>
  )
}

export default App

常见问题 #

1. 类型推断问题 #

如果遇到类型推断问题,确保正确使用泛型:

tsx
// ❌ 错误:类型推断不完整
const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}))

// ✅ 正确:显式定义类型
interface StoreState {
  count: number
  increment: () => void
}

const useStore = create<StoreState>((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}))

2. 模块导入问题 #

确保使用正确的导入方式:

tsx
// ✅ 正确
import { create } from 'zustand'

// ❌ 错误
import create from 'zustand'

3. React 版本兼容性 #

Zustand 需要 React 16.8+(支持 Hooks):

bash
# 检查 React 版本
npm list react

# 如果版本过低,升级 React
npm install react@latest react-dom@latest

总结 #

现在你已经成功安装并配置了 Zustand:

  • ✅ 安装了 Zustand 包
  • ✅ 创建了第一个 store
  • ✅ 在组件中使用了 store
  • ✅ 配置了 TypeScript 支持
  • ✅ 了解了项目结构建议

接下来,让我们深入学习 创建 Store,掌握更多 store 创建技巧。

最后更新:2026-03-28