跳到主要内容

状态管理

项目基于Zustand实现全局状态管理。按模块进行管理,定义在目录src/store

├── src 
│ ├── store
│ ├── settingStore.ts
│ ├── userStore.ts

约定

定义Store时有一些约定需要注意, 以settingStore.ts为例

import { create } from 'zustand';

import { getItem, removeItem, setItem } from '@/utils/storage';

import { StorageEnum, ThemeColorPresets, ThemeLayout, ThemeMode } from '#/enum';

type SettingsType = {
themeColorPresets: ThemeColorPresets;
themeMode: ThemeMode;
themeLayout: ThemeLayout;
themeStretch: boolean;
breadCrumb: boolean;
multiTab: boolean;
};
type SettingStore = {
settings: SettingsType;
// 1: 🚀 使用 actions 命名空间来存放所有的 action
actions: {
setSettings: (settings: SettingsType) => void;
clearSettings: () => void;
};
};

const useSettingStore = create<SettingStore>((set) => ({
settings: getItem<SettingsType>(StorageEnum.Settings) || {
themeColorPresets: ThemeColorPresets.Default,
themeMode: ThemeMode.Light,
themeLayout: ThemeLayout.Vertical,
themeStretch: false,
breadCrumb: true,
multiTab: true,
},
actions: {
setSettings: (settings) => {
set({ settings });
setItem(StorageEnum.Settings, settings);
},
clearSettings() {
removeItem(StorageEnum.Settings);
},
},
}));

// 2: 🚀 将state和actions分别导出
export const useSettings = () => useSettingStore((state) => state.settings);
export const useSettingActions = () => useSettingStore((state) => state.actions);

使用

  • 使用useSettings获取SettingStore中存储的状态
    const { themeMode } = useSettings();
  • 使用useSettingActions获取,操作SettingStore状态的action
    const { setSettings } = useSettingActions();

    const setThemeLayout = (themeLayout: ThemeLayout) => {
    setSettings({
    ...settings,
    themeLayout,
    });
    };