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>
  )
}
相关推荐
ᅠᅠᅠ@几秒前
异常枚举;
开发语言·javascript·ecmascript
小阿飞_1 分钟前
报错合计-1
前端
caperxi3 分钟前
前端开发中的防抖与节流
前端·javascript·html
霸气小男3 分钟前
react + antDesign封装图片预览组件(支持多张图片)
前端·react.js
susu10830189113 分钟前
前端css样式覆盖
前端·css
学习路上的小刘5 分钟前
vue h5 蓝牙连接 webBluetooth API
前端·javascript·vue.js
&白帝&5 分钟前
vue3常用的组件间通信
前端·javascript·vue.js
小白小白从不日白16 分钟前
react 组件通讯
前端·react.js
罗_三金26 分钟前
前端框架对比和选择?
javascript·前端框架·vue·react·angular
Redstone Monstrosity33 分钟前
字节二面
前端·面试