快速上手:5分钟快速起步
欢迎来到 Zustand 的快速入门指南!在本章节中,我们将通过一个简单的示例,带你在 5 分钟内快速掌握 Zustand 的基本用法。
安装 Zustand
首先,让我们安装 Zustand:
bash
# 使用 npm
npm install zustand
# 使用 yarn
yarn add zustand
# 使用 pnpm
pnpm add zustand创建你的第一个 Store
Zustand 的核心概念是 Store(存储),它包含了应用的状态和修改状态的方法(Actions)。
让我们创建一个简单的计数器 Store:
javascript
// src/store/counter.js
import { create } from 'zustand'
// 创建一个 Store
const useCounterStore = create((set) => ({
// 状态
count: 0,
// Actions:修改状态的方法
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}))
export default useCounterStore这个 Store 包含了:
- 一个
count状态,初始值为 0 - 三个 Actions:
increment(增加计数)、decrement(减少计数)和reset(重置计数)
在 React 组件中使用 Store
现在,让我们在 React 组件中使用这个 Store:
jsx
// src/components/Counter.jsx
import React from 'react'
import useCounterStore from '../store/counter'
function Counter() {
// 从 Store 中获取状态和 Actions
const count = useCounterStore((state) => state.count)
const increment = useCounterStore((state) => state.increment)
const decrement = useCounterStore((state) => state.decrement)
const reset = useCounterStore((state) => state.reset)
return (
<div>
<h1>计数器: {count}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>重置</button>
</div>
)
}
export default Counter更简洁的使用方式
你也可以使用解构的方式获取多个状态和 Actions:
jsx
// src/components/Counter.jsx
import React from 'react'
import useCounterStore from '../store/counter'
function Counter() {
// 同时获取多个状态和 Actions
const { count, increment, decrement, reset } = useCounterStore()
return (
<div>
<h1>计数器: {count}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>重置</button>
</div>
)
}
export default Counter注意:使用这种方式会订阅整个 Store,当 Store 中的任何状态发生变化时,组件都会重渲染。在简单应用中这没问题,但在复杂应用中,建议使用前面的方式,只订阅需要的状态。
在多个组件中共享状态
Zustand 的 Store 是全局的,可以在多个组件中共享:
jsx
// src/components/CounterDisplay.jsx
import React from 'react'
import useCounterStore from '../store/counter'
function CounterDisplay() {
// 只订阅 count 状态
const count = useCounterStore((state) => state.count)
return <div>当前计数: {count}</div>
}
export default CounterDisplay现在,Counter 和 CounterDisplay 组件都会共享同一个 count 状态,当一个组件修改状态时,另一个组件也会自动更新。
运行你的应用
现在,让我们在主应用中使用这些组件:
jsx
// src/App.jsx
import React from 'react'
import Counter from './components/Counter'
import CounterDisplay from './components/CounterDisplay'
function App() {
return (
<div className="App">
<Counter />
<CounterDisplay />
</div>
)
}
export default App启动你的应用,你应该能看到一个计数器和一个显示当前计数的组件。点击计数器的按钮,两个组件都会同步更新。
恭喜你
你已经成功创建了你的第一个 Zustand Store,并在 React 组件中使用了它。这就是 Zustand 的基本用法 - 简单、直观、高效。
在接下来的章节中,我们将深入探讨 Zustand 的 核心概念,包括状态管理的最佳实践、性能优化等内容。