我正在 React 建立一些按鈕,觸發從一個到下一個的狀態變更。我的一些按鈕有三種狀態,由枚舉表示。這三種狀態應依連續順序設定。當達到最後一個值時,下一個操作應該再次將狀態設定回枚舉的第一個值。實現這個的巧妙方法是什麼?
import { create } from 'zustand' import { devtools, persist, createJSONStorage } from 'zustand/middleware' import { BackgroundVariant as Background } from 'reactflow'; function nextBackground(background: Background): Background { switch (background) { case Background.Dots: return Background.Cross; case Background.Cross: return Background.Lines; default: return Background.Dots; }; }; interface MenuState { background: Background; toggleBackground: () => void; } export const useMenuStore = create<MenuState>()( devtools( persist( (set) => ({ background: Background.Dots, toggleBackground: () => set((state) => ({ background: nextBackground(state.background) })) }), { name: 'menu-storage', storage: createJSONStorage(() => localStorage), } ) ) );
P粉8019040892024-04-07 00:43:34
下面是一個函數的範例,它接受任何枚舉並將傳回下一個值或第一個值(如果是最後一個值):
function getNextEnumValue>(enumObj: T, currentValue: T[keyof T]): T[keyof T] { const enumValues = Object.values(enumObj); const enumKeys = Object.keys(enumObj) as (keyof T)[]; const currentIndex = enumKeys.findIndex(key => enumObj[key] === currentValue); if (currentIndex === -1) { throw new Error(`Invalid enum value: ${currentValue}`); } const nextIndex = currentIndex + 1; if (nextIndex === enumKeys.length) { return enumObj[enumKeys[0]]; } const nextValue = enumObj[enumKeys[nextIndex]]; if (!enumValues.includes(nextValue)) { throw new Error(`Invalid enum value: ${nextValue}`); } return nextValue; }