我正在 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; }