请问下,zustand是否可以在BModuleSlice中通过get获取AModuleSlice中的变量和方法呢?

我们知道在使用zustand的时候,可以配置多个Slice,

export const createAModuleSlice: StateCreator<AModuleSlice> = (set, get) => ({
  
  aList: [],

  action1: () = > {

  },

  action2: () = > {
    // get可以获取本Slice中定义的变量或方法
  },

})


export const createBModuleSlice: StateCreator<BModuleSlice> = (set, get) => ({

  bList: [],

  action1: () = > {

  },

  action2: () = > {
    // get可以获取本Slice中定义的变量或方法
  },
})

请问下,是否可以在BModuleSlice中通过get获取AModuleSlice中的变量和方法呢?

阅读 940
1 个回答

用 combine 方法组合 Slices:

import create from 'zustand'
import { combine } from 'zustand/middleware'

interface AModuleSlice {
  aList: string[];
  action1: () => void;
}

interface BModuleSlice {
  bList: number[];
  action2: () => void;
}

type StoreState = AModuleSlice & BModuleSlice;

const createAModuleSlice = (set: any, get: () => StoreState): AModuleSlice => ({
  aList: [],
  action1: () => {
    // 操作自己的状态
    set({ aList: ['new item'] })
  }
})

const createBModuleSlice = (set: any, get: () => StoreState): BModuleSlice => ({
  bList: [],
  action2: () => {
    // 访问 A 模块的状态和方法
    const aList = get().aList;
    get().action1();
    
    // 操作自己的状态
    set({ bList: [1, 2, 3] })
  }
})

const useStore = create(
  combine(
    { ...createAModuleSlice((state, payload) => state = { ...state, ...payload }, () => useStore.getState()) },
    { ...createBModuleSlice((state, payload) => state = { ...state, ...payload }, () => useStore.getState()) }
  )
)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题