【问题标题】:Accessing values in NGRX state programmatically以编程方式访问 NGRX 状态中的值
【发布时间】:2021-03-04 20:27:56
【问题描述】:

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

state.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,
}

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

action.ts

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

reducer.ts

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

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

【问题讨论】:

    标签: angular rxjs ngrx


    【解决方案1】:

    忘了这是一个状态中的对象,只需要调整reducer在action.payload分配周围添加一个括号。

    更新了 reducer.ts

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

    【讨论】:

      【解决方案2】:

      对象键的计算属性名称 - 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]
      

      【讨论】:

        猜你喜欢
        • 2022-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 2018-04-11
        • 2010-09-05
        相关资源
        最近更新 更多