首页 > 解决方案 > 以编程方式访问 NGRX 状态中的值

问题描述

我有一个 NGRX 状态设置,它是一个值的对象。值键是带有布尔值的数字 (1-5)。

状态.ts

export interface State {
  1: boolean;
  2: boolean;
  3: boolean;
  4: boolean;
  5: boolean;
}

export const initialState: State = {
  1: true,
  2: true,
  3: true,
  4: true,
  5: true,
}

我还有一个通过它传递对象编号值的操作。所以在我的减速器中,我正在获取数值,在对象中找到该值,然后切换布尔值。但是,我遇到了一个问题,即我无法在减速器功能中选择对象键,而无需实际输入物理数字。

动作.ts

export const changeButtonState = createAction(
  '[Bingo Actions] Change Button State',
  (payload: number) => ({payload}),
);

减速器.ts

export const reducer = createReducer(
  initialState,
  on(BingoActions.changeButtonState, (state, action) => {
    return {
      ...state,
      action.payload: !state[action.payload],
    };
  })
);

如何在无需在 reducer 函数中物理输入数字的情况下访问对象的数字值?

标签: angularrxjsngrx

解决方案


对象键的计算属性名称 - https://ui.dev/computed-property-names/

export const stateKeys = {
  one: 1,
  two: 2,
  ...
export interface State {
  [stateKeys.one]: boolean;
  [stateKeys.two]: boolean;
...

然后要在 reducer 中使用计算名称访问属性,语法是:

state[stateKeys.one]

推荐阅读