文档
入门指南
安装
使用 npm 或 yarn 安装 Zustand:
npm install zustand # or yarn add zustand # or pnpm add zustand你的第一个 Store
创建一个 store 非常简单。这是一个简单的计数器示例:
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 }),
}))基本用法
在你的 React 组件中使用 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>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
)
}核心概念
Store
Store 保存你的应用程序状态。它是使用 `create` 函数创建的,并返回一个 React hook。
状态
状态是你的 store 保存的数据。它可以是任何 JavaScript 值 - 对象、数组、基本类型等。
操作
操作是修改状态的函数。它们使用 `set` 函数来更新 store。
选择器
选择器允许你订阅状态的特定部分,从而优化重新渲染。