灵感来源于 Flux 的实践
尽管 Zustand 是一个无偏见的库,但我们确实推荐一些模式。这些模式受到最初在 Flux 中发现的实践的启发,最近在 Redux 中也有所发现,所以如果你来自其他库,你应该感到非常熟悉。
然而,Zustand 在一些基本方面确实有所不同,所以一些术语可能不会完全对应其他库。
推荐的模式
单一存储
你的应用程序全局状态应该位于一个单一的 Zustand 存储中。
如果你有一个大型应用程序,Zustand 支持将存储分割成切片。
使用 set /setState 来更新存储
始终使用 set(或 setState)来对你的存储进行更新。set(和 setState)确保所描述的更新被正确地合并,监听器被适当地通知。
集中存储操作
在 Zustand 中,状态可以在不使用其他 Flux 库中的分派操作和 reducers 的情况下进行更新。这些存储操作可以直接添加到存储中,如下所示。
另外,通过使用 setState,它们可以位于存储外部
const useBoundStore = create((set) => ({ storeSliceA: ..., storeSliceB: ..., storeSliceC: ..., updateX: () => set (...), updateY: () => set (...),}))
类似 Redux 的模式
如果你不能没有类似 Redux 的 reducers,你可以在存储的根级别定义一个 dispatch 函数:
const types = { increase: 'INCREASE', decrease: 'DECREASE' }
const reducer = (state, { type, by = 1 }) => { switch (type) { case types.increase: return { grumpiness: state.grumpiness + by } case types.decrease: return { grumpiness: state.grumpiness - by } }}
const useGrumpyStore = create((set) => ({ grumpiness: 0, dispatch: (args) => set((state) => reducer (state, args)),}))
const dispatch = useGrumpyStore((state) => state.dispatch)dispatch ({ type: types.increase, by: 2 })
你也可以使用我们的 redux-middleware。它连接你的主 reducer,设置初始状态,并向状态本身和 vanilla api 添加一个 dispatch 函数。
import { redux } from 'zustand/middleware'
const useReduxStore = create(redux (reducer, initialState))
更新存储的另一种方式可能是通过函数包装状态函数。这些也可以处理操作的副作用。例如,使用 HTTP 调用。要以非反应式的方式使用 Zustand,参见 readme。