我正在尝试使用枚举值设置 redux 切片的初始状态,但它会抛出
Uncaught TypeError: undefined has no properties
。
代码是:
export const themeTokenSlice = createSlice({
name: "themeToken",
initialState: darkThemeToken,
reducers: {
toggleThemeToken: (state) => {
switch (state.theme) {
case Themes.dark:
state = darkThemeToken;
break;
case Themes.light:
state = lightThemeToken;
break;
default:
return state;
}
}
}
});
export const darkThemeToken: themeState = {
theme: Themes.dark
};
export interface themeState {
theme: Themes;
}
export enum Themes {
dark = "dark",
light = "light",
}
它的工作原理:
export const darkThemeToken: themeState = {
theme: "dark" as Themes.dark,
colorPrimary: '#f01879',
colorLink: '#f01879',
colorLinkHover: '#f66eab',
colorBgBase: '#242424',
};
有没有办法用枚举来初始化状态?
这就是你的代码应该是什么样的(我认为是这样) 但您遇到了类型问题,现在应该得到解决
export interface themeState {
theme: Themes;
colorPrimary: string,
colorLink: string,
colorLinkHover: string,
colorBgBase: string,
}
export enum Themes {
dark = "dark",
light = "light",
}
export const darkThemeToken: themeState = {
theme: "dark" as Themes.dark,
colorPrimary: '#f01879',
colorLink: '#f01879',
colorLinkHover: '#f66eab',
colorBgBase: '#242424',
};
export const lightThemeToken: themeState = {
theme: "dark" as Themes.dark,
colorPrimary: '#f01879',
colorLink: '#f01879',
colorLinkHover: '#f66eab',
colorBgBase: '#242424',
};
export const themeTokenSlice = createSlice({
name: "themeToken",
initialState: darkThemeToken,
reducers: {
toggleThemeToken: (state: themeState) => {
switch (state.theme) {
case Themes.dark:
state = darkThemeToken;
break;
case Themes.light:
state = lightThemeToken;
break;
default:
return state;
}
}
}
});