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>
  )
}
相关推荐
神奇的程序员7 小时前
我的软件冲进苹果商店下载榜前 50 了
前端
阳光是sunny8 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
万少9 小时前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
尘世中一位迷途小书童11 小时前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript
IT_陈寒12 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
月光下的丝瓜13 小时前
Flutter 国内安装指南
前端·flutter
先吃饱再说13 小时前
JavaScript中`this` 的“千层套路”:从默认绑定到箭头函数的五种指向
javascript
玄星啊13 小时前
AI 编程的第 30 天,我怀念古法 Coding 了
前端·ai编程
Jolyne_13 小时前
Angular基础速通
前端·angular.js
foxire13 小时前
基于nodejs实现服务端内核引擎
javascript