欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > zustand 切片模式使用,persist 中间件持久化状态

zustand 切片模式使用,persist 中间件持久化状态

2025/2/23 10:47:58 来源:https://blog.csdn.net/lryh_/article/details/145182231  浏览:    关键词:zustand 切片模式使用,persist 中间件持久化状态

zustand - npm

安装 npm i zustand

创建切片目录:

创建切片 channelStore.js

import { getChannelsAPI } from "@/apis/article";
const channelStore = (set) => {return {channelList: [],fetchChannelList: async () => {const res = await getChannelsAPI()set({channelList: res.data.data.channels})}}
}
export default channelStore

创建切片numStore.js

const numStore = (set) => {return {num: 0,incre: ()=>{set(state => ({num: state.num+1}))}}
}
export default numStore
创建主Store 如  useStoree 并组合切片
import { create } from "zustand";
import channelStore from "./module/channelStore";
import numStore from "./module/numStore";const useStoree = create((...args) =>{return {...channelStore(...args),...numStore(...args)}
})
export default useStoree

或者

import { create } from 'zustand';
import channelStore  from './module/channelStore';
import numStore  from './module/numStore';const useStoree = create(set => ({...channelStore(set),...numStore(set)
}))export default useStoree

在组件中使用useStoree 

import useStoree from "@/zustandStore";
import { useEffect } from "react";const ZustanInd = ()=>{// const num = useStoree((state) => state.num)// const fetchChannelList = useStoree((state) => state.fetchChannelList)// const channelList = useStoree((state) =>state.channelList)// const incre = useStoree((state) => state.incre)const {num,incre,fetchChannelList,channelList} = useStoree()useEffect(()=>{fetchChannelList()},[])console.log(channelList)return<><button onClick={incre}>{num}</button><ul>{channelList.map(item=><li key={item.id}>{item.name}</li>)}</ul></>
}
export default ZustanInd

使用 persist 中间件 持久化状态

npm install zustand/persist

import { create } from 'zustand';
import channelStore  from './module/channelStore';
import numStore  from './module/numStore';
import { persist } from 'zustand/middleware';
const useStoree = create(persist(set => ({...channelStore(set),...numStore(set)}),{name: 'my-store', // 存储的名字getStorage: () => localStorage, // 存储的方式})
)export default useStoree

持久化部分:

import { create } from 'zustand';
import channelStore  from './module/channelStore';
import numStore  from './module/numStore';
import { persist } from 'zustand/middleware';
const useStoree = create(persist((set) => ({...channelStore(set),...numStore(set)}),{name: 'my-store', // 存储的名字getStorage: () => localStorage, // 存储的方式 ,默认是 localStorage,也可设置 sessionStoragepartialize: (state) => ({ num: state.num }), // 持久化部分状态})
)export default useStoree

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词