zustand - 状态管理
Zustand 是一个轻量、快速且灵活的 React 状态管理库
同步修改
//zustand
import { create } from "zustand"//1.创建store//①:函数参数必须返回一个对象 对象内部编写状态数据和方法
//②:set是用来修改数据的专门方法必须调用它来修改数据
// 语法1:参数是函数, 需要用到老数据的场景
// 语法2:参数直接是一个对象 set({count : 100})
const useStore = create((set)=>{return {//状态数据count: 0,//修改状态数据的方法inc:()=>{set((state)=>({count:state.count +1}))}}
})//2. 绑定store到组件
//useStore => {count , inc}function PreZustand(){const {count,inc} = useStore()return (<><button onClick={inc}>{count}</button></>)
}export default PreZustand
异步支持
在函数中编写异步逻辑,最后只需要调用set方法传入新状态即可
//zustand
import { useEffect } from "react"
import { create } from "zustand"
const URL = ''
//1.创建storeconst useAsyncStore = create((set)=>{return {channelList: [],fetchGetList:async()=>{const res = await fetch(URL)const jsonRes = await res.json()console.log(jsonRes)set({channelList: jsonRes.data.channels})}}
})//2. 绑定store到组件function PreZustand(){const {fetchGetList,channelList} = useAsyncStore()useEffect(()=>{fetchGetList()},[fetchGetList])return (<><ul>{channelList.map(item=><li key={item.id}>{item.name}</li>)}</ul></>)
}export default PreZustand
切片模式
场景:当单个store比较大的时候,可以采用切片模式进行模块拆分组合,类似于模块化
import { useEffect } from "react"
import { create } from "zustand"
const URL = 'http://geek.itheima.net/v1_0/channels'//1.拆分子模块 再组合起来//创建counter相关的切片
const createCounterStore = (set)=>{return {//状态数据count: 0,//修改inc: ()=>{set(state => ({count:state.count +1}))}}
}//创建channel相关切片
const createChannelStore = (set)=>{return {channelList: [],fetchGetList: async ()=>{const res = await fetch(URL)const jsonData = await res.json()set({channelList: jsonData.data.channels})}}
}//组合切片
const useStore = create((...a) => ({...createCounterStore(...a),...createChannelStore(...a)
}))function PreZustand2(){const {count,inc,channelList,fetchGetList} = useStore()useEffect(()=>{fetchGetList()},[fetchGetList])return (<><button onClick={inc}>{count}</button><ul>{channelList.map((item)=>(<li key={item.id}>{item.name}</li>))}</ul></>)}export default PreZustand2