分别创建文件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>
)
}