• 简体中文
  • 不使用 store action 的实践

    推荐的做法是把 action 与状态一起放在 store 内部(让 action 和状态待在一起)。

    例如:

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

    这样创建的 store 是自包含的,数据和 action 都在其中。


    另一种做法是在模块层级定义 action,也就是把它们放在 store 之外。

    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 })

    这样做有几个好处:

    • 调用 action 时不需要 Hook;
    • 便于代码分割。

    这种模式本身并没有什么缺点,但由于就近放置(colocation)具有封装性,有些人可能更偏好把 action 与状态放在一起。