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,也可设置 sessionStorage
            partialize: (state) => ({ num: state.num }), // 持久化部分状态
          }
    )
)

export default useStoree
相关推荐
vvilkim4 小时前
全面解析React内存泄漏:原因、解决方案与最佳实践
前端·javascript·react.js
vvilkim4 小时前
React批处理(Batching)更新机制深度解析
前端·javascript·react.js
进取星辰5 小时前
12、高阶组件:魔法增幅器——React 19 HOC模式
前端·javascript·react.js
Aphasia3119 小时前
react必备JS知识点(一)——判断this指向👆🏻
前端·javascript·react.js
全栈派森11 小时前
Next15 + Prisma + Auth5 实战讲解
react.js·node.js·next.js
孟陬11 小时前
umi VS umi max 如何技术选型
react.js
萌萌哒草头将军16 小时前
🚀 REST API 还是 ✈️ GraphQL ❓
前端·vue.js·react.js
just小千16 小时前
重学React(一):描述UI
前端·react.js·ui
lifeAdventure18 小时前
React-Router 简单实践一图流
react.js
CF14年老兵18 小时前
Next.js 全页面缓存实践:如何为 SSR 页面提速而不失新鲜度
前端·react.js·next.js