本文意在作为学习Zustand的引导文章,希望各位可以通过此篇文章达到初步入门或者是复习的效果
如果你是第一次接触状态管理工具的话,希望你可以去自行搜索一下状态管理工具的作用和一些常见工具的使用方法,如果你是用过Redux
,那么强烈推荐你使用Zustand
来进行更为便捷的状态管理,它简单易懂,非常适合新手快速上手!
npm install zustand # or yarn add zustand
创建的 store 是一个 hook
,你可以放任何东西到里面:基础变量,对象、函数,状态必须不可改变地更新,set
函数合并状态以实现状态更新。
import { create } from 'zustand'
const useBearStore = create((set) => ({
bears: 0,
// 基于老数据进行计算
// 需要有state的原因是:需要依赖与当前的bears的状态值进行计算
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
// 直接修改老数据
// 不需要有state的原因是:不需要以来当前bears的状态值,因为它只是将bears进行重置
removeAllBears: () => set({ bears: 0 }),
}))
可以在任何地方使用钩子,不需要提供 provider
。
基于 selector
获取您的目标状态,组件将在状态更改时重新渲染。
function BearCounter() {
const bears = useBearStore((state) => state.bears)
return <h1>{bears} around here ...</h1>
}
function Controls() {
const increasePopulation = useBearStore((state) => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}
import { useBearStore } from './xx'
const { bears, increasePopulation, setPopulation, removeAllBears } = useBearStore()
// 使用...
衡量一个状态管理工具的好坏,相信对于异步操作的支持也是非常重要的一个指标
Zustand的异步不需要特殊的操作,直接在函数中编写异步逻辑,最后只需要调用set方法传入新状态即可
import { create } from 'zustand'
const useTestStore = create((set) => ({
count: 1,
list: [],
fetchGetList: async(URL) => ({
try {
const res = await fetch(URL)
const json = await res.json
// 在原有的基础上count的值
set((state) => ({count: state.count + 1 }))
// 重置list的值
set({list: json.listContext})
} catch(error) {
console.log(error)
}
})
}))
当单个store比较大的时候,可以采用切片模式进行模块拆分组合,类似于模块化
// 文件一
const useTestOneStore = (set) => ({
xxx
})
// 文件二
const useTestTwoStore = (set) => ({
xxx
})
// 组合切片(通常单独放置一个文件)
// 引入后...
const useStore = create((...a) => ({
...useTestOneStore(...a),
...useTestTwoStore(...a)
}))
在使用的时候:
import React from 'react';
import useStore from './xxx'; // 根据实际路径调整
const App = () => {
// 解构操作
const { count, increment, name, setName } = useStore()
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<h1>Name: {name}</h1>
<button onClick={() => setName('new name')}>Set Name</button>
</div>
)
}
export default App;
在最后总结一下Zustand的好处
Provider
,直接使用 hook
即可管理状态(此处的Provider
指React
中useContext
)set
函数来更新状态,状态更新必须是不可变的。Store
拆分成多个模块,类似于Redux
的模块化处理方式。我们不难发现,它是一款简单易用的状态管理工具,一定程度上让使用状态管理变得简单容易,真心推荐你来试一试!
很高兴你可以看到这里,如果有相关的其他问题你可以留言或者私信,我会尽我最大可能帮助你!