React zustand

本文最后更新于:2024年4月25日 上午

zustand是一个React的状态管理包,使用hooks的方式来使用(像Pinia一样)

官方文档:

Zustand (github.com)

安装

1
pnpm i zustand

创建一个状态库

zustand暴露create方法用于创建store

create方法接收() => object回调函数

src/store/userStore.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import create from 'zustand'

const store = () => {
return {
name: '芸',
balance: 0,
}
}

const useUserStore = create(store)

export { useUserStore }

获取状态

useUserStore函数可以直接调用将返回整个store,进行解构后依然具有响应式,但所有操作更新(比如balance + 0与原状态相同)都会导致组件重新渲染(函数重新执行)

也可传递一个回调函数来筛选所需的单个数据这样组件不会在状态不变时重新渲染

src/App.jsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { useUserStore } from './store/userStore'

export function App() {
useUserStore((...args) => console.log('useUserStore', args))
/*
* [{
* name: '芸',
* balance: 0,
* }]
*/

// 下面两种状态与旧值相同也会使组件重新渲染
// const { name, balance } = useUserStore()
// const [name, balance] = useUserStore(({ name, balance }) => [name, balance])

const name = useUserStore((state) => state.name)
const balance = useUserStore(({ balance }) => balance)

return (
<>
<p>用户: {name}</p>
<p>余额: {balance}</p>
</>
)
}

方法

1

状态持久化


React zustand
https://qingshaner.com/zustand/
作者
清山
发布于
2022年11月5日
许可协议