zustand状态管理工具(react)

分别创建文件continue.js、shoes.js

1、continue.js

javascript 复制代码
import create from 'zustand'
import { persist } from 'zustand/middleware'


export default create(
  persist(
    (set) => ({
      counter: 12,
      incrementer: () => set((state) => ({ counter: state.counter + 1 })),
      decrementer: () => set((state) => ({ counter: state.counter - 1 }))
    }),
    {
      name: 'myStore' // 持久化状态的标识符,用于存储在 localStorage 或其他存储中
    }
  )
)

2、shoes.js

javascript 复制代码
import create from 'zustand'

const useStore1 = create((set) => ({
  count: 12,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 }))
}))

export default useStore1

项目中使用

javascript 复制代码
import React from 'react'
import useStore1 from '@/zustandStore/shoes.js'
import useStore2 from '@/zustandStore/continue.js'
import styles from './index.module.scss'


export default function index() {
  const { count, increment, decrement } = useStore1()
  const { counter, incrementer, decrementer } = useStore2()


  return (
    <div className={styles.tableBox}>
      <div>
        普通的值:{count}
        <button onClick={() => increment()}>新增</button>
      </div>
      <div>
        长保存的值(localStorage):{counter}
        <button onClick={() => incrementer()}>新增</button>
      </div>
    </div>
  )
}
相关推荐
步行cgn8 分钟前
JSON.stringify 详解:把 JavaScript 对象变成 JSON 字符串
开发语言·javascript·json
Liben11 分钟前
Weex开发踩坑记录
android·前端·ios
jerrywus25 分钟前
AI 写的代码能跑,为什么接手的人想跑?
前端·agent·claude
山雀~31 分钟前
Web 多语言(i18n)技术方案详解
前端
biu_biubiu1 小时前
我开源了 Codebook
前端·vue.js
下山1 小时前
怎么把带自研插件的 DeepSeek Harness 部署到云服务器
前端
彭亚川Allen1 小时前
985 在职研究生到底怎么样?是不是水硕?是不是.....?
前端·后端·程序员
YufJi1 小时前
两棵树,两个线程:一个小程序引擎的架构拆解
前端
super_Omni1 小时前
Chrome 插件入驻实战:从 Manifest V3 到过审上架的完整路径
大数据·前端·chrome
腾讯数据架构师2 小时前
任务跑完怎么直接出图表?CubeStudio 任务可视化 ECharts 数据格式实操(CSV/JSON + metric.json,11 种图表一键渲染)
前端·json·echarts·数据可视化