使用 zustand 作为 React 状态管理库
2025 年 1 月 10 日
zustand 介绍
zustand 基本用法
安装
bash
npm install zustand
创建 store
javascript
import create from "zustand"
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
create
方法是一个工厂函数,它接受一个函数作为参数,这个函数接收一个set
方法作为参数,这个set
方法可以用来更新 store 中的状态。useStore
是一个 React hook,它返回一个对象,这个对象包含了 store 中的状态和更新状态的方法。
使用 store
javascript
function Counter() {
const { count, increment } = useStore()
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
)
}
useStore
hook 返回的对象包含了 store 中的状态和更新状态的方法。count
是一个状态,它的值会随着组件的渲染而更新。increment
是一个方法,它会更新count
状态。