zustand状态管理工具(react)

发布时间:2024年01月10日

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

1、continue.js

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

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

项目中使用

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>
  )
}
文章来源:https://blog.csdn.net/qq_60178319/article/details/135499102
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。