参考zustand:
https://zustand.docs.pmnd.rs/guides/slices-pattern#slices-pat...
我们可以使用slice的方式进行区分出store
//FishSlice
export const createFishSlice = (set) => ({
fishes: 0,
addFish: () => set((state) => ({ fishes: state.fishes + 1 })),
})
//BearSlice
export const createBearSlice = (set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),
})
但是我们可以看到是注册合并在一起的:
import { create } from 'zustand'
import { createBearSlice } from './bearSlice'
import { createFishSlice } from './fishSlice'
export const useBoundStore = create((...a) => ({
...createBearSlice(...a),
...createFishSlice(...a),
}))
使用:我们可以看到是使用总体的store(useBoundStore)
import { useBoundStore } from './stores/useBoundStore'
function App() {
const bears = useBoundStore((state) => state.bears)
const fishes = useBoundStore((state) => state.fishes)
const addBear = useBoundStore((state) => state.addBear)
return (
<div>
<h2>Number of bears: {bears}</h2>
<h2>Number of fishes: {fishes}</h2>
<button onClick={() => addBear()}>Add a bear</button>
</div>
)
}
export default App
现在有一个疑问就是,是否是不同的Slice内的属性和方法都应该在全局唯一?如果项目变大了,store的slice多了,那么怎么保障全局唯一呢?
为什么要保证全局唯一?
slice 是为了避免单个 store 过大的,又没说全局只能有一个 store。
你把毫不相干的一堆状态放到一个 store 里干啥?不同的 store 状态重名就重名了呗。