让人爱不释手的状态管理工具——Zustand的基础讲解

写在前面

本文意在作为学习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 }),
}))

Store 绑定组件,就完成了!

可以在任何地方使用钩子,不需要提供 provider
基于 selector 获取您的目标状态,组件将在状态更改时重新渲染。

选择目标状态:bears

function BearCounter() {
  const bears = useBearStore((state) => state.bears)
  return <h1>{bears} around here ...</h1>
}

更新目标状态:bears

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的异步支持

衡量一个状态管理工具的好坏,相信对于异步操作的支持也是非常重要的一个指标

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)
        }
    })
}))

Zustand切片模式

当单个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的好处

  1. 简单易用:无需配置 Provider,直接使用 hook 即可管理状态(此处的ProviderReactuseContext)
  2. 不可变状态更新:通过 set 函数来更新状态,状态更新必须是不可变的。
  3. 函数和异步支持:支持将函数放入状态中,可以轻松处理异步操作。
  4. 高效性能:组件只在特定状态更改时重新渲染,避免了不必要的性能开销。
  5. 模块化支持:通过切片模式(Slice)来将大型Store拆分成多个模块,类似于Redux的模块化处理方式。

我们不难发现,它是一款简单易用的状态管理工具,一定程度上让使用状态管理变得简单容易,真心推荐你来试一试!
很高兴你可以看到这里,如果有相关的其他问题你可以留言或者私信,我会尽我最大可能帮助你!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tabzzz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值