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>
  )
}
相关推荐
Csvn6 分钟前
并发模式:让渲染学会排队、插队和让路
前端
可乐鸡翅yeah_19 分钟前
新手梳理:M3U8 线上问题,哪些是前端锅,哪些是后端锅
前端·ios·音视频·实时音视频·m3u8·音视频在线播放
Flynt20 分钟前
Linear 用 1000 个 PR 换掉 styled-components,我写了 200 个按钮,把这笔账复现了一遍
前端·css·preact
JavaGuide1 小时前
NVIDIA 又开源了!这次给 AI Agent 加上权限管控
前端·后端
excel2 小时前
prisma 如何处理数据库竞态
前端·数据库·后端
莪_幻尘3 小时前
Skill 体检:30 个 Skill 全凭感觉?体检器先自曝了 8 个“假 0 分
前端·人工智能·llm
风骏时光牛马3 小时前
AI模型综合能力评测:性能、指令遵循与多场景实测对比
前端
Frag0ut3 小时前
Chrome与Chromium内核浏览器在Windows 11上的新特性全景解析
前端·chrome·windows·web安全·chromium·gemini ai·playready drm
hiahiahia1234 小时前
实现完整 Tool Dispatcher
开发语言·前端
IT_陈寒4 小时前
Java线程池这破玩意,差点让我周末加班排查到凌晨
前端·人工智能·后端