分别创建文件continue.js、shoes.js
1、continue.js文章来源:https://www.toymoban.com/news/detail-822751.html
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文章来源地址https://www.toymoban.com/news/detail-822751.html
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>
)
}
到了这里,关于zustand状态管理工具(react)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!