如何使用枚举值初始化 redux 切片?

问题描述 投票:0回答:1

我正在尝试使用枚举值设置 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',
};

有没有办法用枚举来初始化状态?

javascript reactjs typescript redux redux-toolkit
1个回答
0
投票

这就是你的代码应该是什么样的(我认为是这样) 但您遇到了类型问题,现在应该得到解决

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;
          }
      }
  }
});

© www.soinside.com 2019 - 2024. All rights reserved.