Skip to content

不使用存储操作的实践

¥Practice with no store actions

建议的用法是将操作和状态放在存储中(让你的操作与你的状态放在一起)。

¥The recommended usage is to colocate actions and states within the store (let your actions be located together with your state).

例如:

¥For example:

js
export const useBoundStore = create((set) => ({
  count: 0,
  text: 'hello',
  inc: () => set((state) => ({ count: state.count + 1 })),
  setText: (text) => set({ text }),
}))

这将创建一个包含数据和操作的独立存储。

¥This creates a self-contained store with data and actions together.


另一种方法是在存储外部的模块级别定义操作。

¥An alternative approach is to define actions at module level, external to the store.

js
export const useBoundStore = create(() => ({
  count: 0,
  text: 'hello',
}))

export const inc = () =>
  useBoundStore.setState((state) => ({ count: state.count + 1 }))

export const setText = (text) => useBoundStore.setState({ text })

这有几个优点:

¥This has a few advantages:

  • 它不需要钩子来调用操作;

    ¥It doesn't require a hook to call an action;

  • 它有助于代码拆分。

    ¥It facilitates code splitting.

虽然这种模式没有任何缺点,但有些人可能更喜欢共置,因为它具有封装性质。

¥While this pattern doesn't offer any downsides, some may prefer colocating due to its encapsulated nature.

Zustand v5.0 中文网 - 粤ICP备13048890号