嵌套Redux Reducer中的解构动作

时间:2019-07-06 17:33:04

标签: javascript reactjs ecmascript-6 redux state

我正在调度如下所示的动作:

{ type: "TOGGLE_FARA", fara: true, id: "5d20d019cf42731c8f706db1" }

“ id”仅用于识别正确的用户。该操作旨在修改我的“ fara”状态的“ enabled”属性。我商店的fara部分如下所示:

{
   fara: {
     enabled: false, // This need to be flipped...
     names: []
   },
   senators: {
      enabled: false,
      names: []
   },
   senateCandidates: {
      enabled: false,
      names: []
   }
}

但是,我不确定如何构造减速器。我只想更改“已启用”属性。我尝试了几种不同的方法:

export default (state = DEFAULT_STATE, action) => {
    switch (action.type) {
      case "INITIALIZE_SETTINGS":
        return {
          fara: action.fara,
          senators: action.senators,
          senateCandidates: action.senateCandidates,
          emails: action.emails
        }
      case "TOGGLE_FARA":
        return {
          ...state,
          // fara['enabled']: action.fara <–– This won't compile...
          // 'fara.enabled' : action.fara <–––This just gives me a key name with the string 'fara.enabled' 
        }
      default:
        return state;
      }

我打算做这样的事情,但是这会直接修改您不应该做的状态(我的redux工具扩展说状态是相同的,这并不理想)。有什么想法吗?

export default (state = DEFAULT_STATE, action) => {
    switch (action.type) {
      case "INITIALIZE_SETTINGS":
        return {
          fara: action.fara,
          senators: action.senators,
          senateCandidates: action.senateCandidates,
          emails: action.emails
        }
      case "TOGGLE_FARA":
        state.fara.enabled = action.fara;
        return {
           ...state
        };
      default:
        return state;
      }

1 个答案:

答案 0 :(得分:5)

这将起作用:

return {
          ...state,
          fara: { ...state.fara, enabled: action.fara }
        }

而且显然甚至在Redux documentation