zustand如何进行监听属性的变化?
比如我有:Slice如下:
export interface SectionSlice {
Sections: Section[],
selectedSection: Section | undefined,
isLoading: boolean,
selectSection: (SectionID: number) => void,
fetchSections: () => Promise<void>,
addSection: (Section:Section) => Promise<void>,
updateSection: (Section:Section) => Promise<void>,
deleteSection: (id: number) => Promise<void>,
SectionMods: SectionMod[],
selectedSectionMod: SectionMod | undefined,
selectSectionMod: (SectionModId: number) => Promise<void>,
fetchSectionMods: (SectionId: number) => Promise<void>,
}
//type SliceType = StateCreator<SectionSlice, [], [], SectionSlice>
export const createSectionSlice: StateCreator<SectionSlice> = (set, get) => ({
// 1.状态
Sections: [] as Section[],
selectedSection: undefined as Section | undefined,
SectionMods: [] as SectionMod[],
selectedSectionMod: undefined as SectionMod | undefined,
// 2.操作状态的actions
isLoading: false, // 是否正在操作
fetchSections: async() => {
try {
set({ isLoading: true })
const Sections: Section[] = await getSections()
set({ Sections: Sections })
} catch (error) {
} finally {
set({ isLoading: false })
}
},
// 选择项目
selectSection: (SectionID: number) => {
// 基于SectionID获取Section
const { Sections } = get()
const filteredSection = (Sections as Section[]).filter((Section: Section) => Section.id === SectionID);
set({ selectedSection: filteredSection[0] })
},
addSection: async(Section:Section) => {
try {
set({ isLoading: true })
await addSection(Section)
} catch (error) {
} finally {
const { fetchSections } = get(); // 通过get获取当前状态里的fetchSections方法
fetchSections()
set({ isLoading: false })
}
},
updateSection: async(Section: Section) => {
try {
set({ isLoading: true })
await updateSection(Section)
} catch (error) {
} finally {
const { fetchSections } = get(); // 通过get获取当前状态里的fetchSections方法
fetchSections()
set({ isLoading: false })
}
},
deleteSection: async(id: number) => {
try {
set({ isLoading: true })
await deleteSection(id)
} catch (error) {
} finally {
const { fetchSections } = get(); // 通过get获取当前状态里的fetchSections方法
fetchSections()
set({ isLoading: false })
}
},
selectSectionMod: async(SectionModId: number) => {
// 基于SectionID获取Section
const { SectionMods } = get()
const filteredSectionMod = (SectionMods as SectionMod[]).filter((SectionMod: SectionMod) => SectionMod.id === SectionModId);
set({selectedSectionMod: filteredSectionMod[0]})
},
fetchSectionMods: async(SectionId: number) => {
try {
set({ isLoading: true })
const SectionMods: SectionMod[] = await getSectionMods(SectionId)
set({ SectionMods: SectionMods })
const { selectedSectionMod } = get()
if( !selectedSectionMod ) {
const mainSectionMods: SectionMod[] = SectionMods.filter((SectionMod) => SectionMod.isMain === true);
set({ selectedSectionMod: mainSectionMods[0]})
}
} catch (error) {
} finally {
set({ isLoading: false })
}
},
})
我想要在Store内(可以是Slice中)中监听:selectedSection 变化(比如:我想要知道selectedSection改变之后,立即就触发方法,在方法里面操作),在监听的事件里面在做其他的操作。
用的时候: