如何在 Redux 中正确创建新状态?

How to properly create a new state in Redux?

在我的 Angular 应用程序中使用 Redux,并在 Switch 语句 中的每个 Case 中简单地创建一个新状态。然而,尽管我的代码工作得很好,但我对 我在每个案例中克隆我的对象 的方式感到不舒服,所以有 更好的 cleaner的克隆方式呢?如何改进 Case 语句?提前致谢!

这是我的

接口:

export interface AppState {
  session: {},
  uiState: {
    summary: {
      summaryDetail: {
        headerTitle: string;
        expandSummaryDetailPanel: boolean;
        showSummaryDetail: boolean;
        someProperty: string;
       }
       showSummaryTab: boolean;
    }
  }
}; 

初始状态:

export const initialState: AppState = {
  session: {},
  uiState: {
    summary: {
      summaryDetail: {
        headerTitle: 'new title',
        expandSummaryDetailPanel: false,
        showSummaryDetail: false,
        someProperty: ''
      },
      showSummaryTab: false,
    }
  }
};

切换语句:

export function appReducer(state = initialState, action: appActions.AppAction) { 

 case appActions.EXPAND_SUMMARY_DETAIL_PANEL: {
  return {
    ...state,
    uiState: {
      summary: {
        ...state.uiState.summary,
        summaryDetail: {
          ...state.uiState.summary.summaryDetail,
          expandSummaryDetailPanel: action.payload
        }
      }
    }
  }
 }
}

你需要额外的库来避免重复嵌套如果你的状态实际上必须是这么深的嵌套。 我会先尝试以不同的方式(更平坦)对状态建模。但如果这在某种程度上不是一种选择,你可以这样做:

case appActions.EXPAND_SUMMARY_DETAIL_PANEL:
    // Find a library that clones objects or use something like immutablejs.
    const newState = deepClone(state);
    newState.uiState.summary.summaryDetail.expandSummaryDetailPanel = action.payload;
    return newState;

一些注意事项:

  • 您所在州的房产经常重复 "summary" 这个词。 state.summary.detail.expandPanel 是否也能工作并具有足够的表现力?
  • uiState 读起来就像你在表达 where 状态被使用,但是 redux 不必关心这个。这种类型的映射发生在 mapStateToProps 中。或者至少将其缩短为 state.ui.