在 React Redux 中更新深层嵌套状态(规范化)

Update deep nested state (normalized) in react redux

我正在尝试在 React / Redux 中创建一个航班搜索应用程序,在主屏幕中将显示我所有的航班结果,并在侧边栏中显示不同类型的过滤器作为复选框。 (例如,参见 this example

过滤器按类型分组,例如出发站、到达站、出发时间等。所有过滤器元素都在一个规范化的嵌套状态中创建,其中每个元素具有以下属性:

"type": "airlines",           // this is the group type 
"checked": true,              // will be switched true or false
"label": "Brittish Airways"   // this is the display label

当我在 React 视图中单击其中一个复选框时,将触发以下操作:

export function filterFlightOffers(item, index) {
    return {
        type: 'FILTER_FLIGHT_OFFERS',
        grouptype,
        id
    }
}

我希望我的 redux reducer 更新状态(切换检查值)和 return 新状态(例如不可变)。查看在线示例,我对解决方案做出反应,例如使用扩展运算符复制新状态,例如...使用切换的检查项目声明和更新特定元素,例如{[action.id]:已检查,已检查}。

但我就是无法让它工作,我想是因为我有一个很深的嵌套状态。因此我删除了动作和 reducer 的复杂性并制作了一个简单的 jsfiddle,它应该只是 console.log一个新的不可变 'changed' 状态。

有没有人可以帮助我?

http://jsfiddle.net/gzco1yp7/4/

谢谢!

如果您的状态看起来像这样:

{    
  result: [1,2,3,4],
  entities: {
    searchitems: {
      1: {
        "type": "matchAirlines",
        "checked": false,
        "label": "Match airlines"
      }, 
      2: {
        "type": "airlines",
        "checked": true,
        "label": "Air France"
      },
      3: {
        "type": "airlines",
        "checked": true,
        "label": "Brittish Airways"
      }
    }, 
    counts:
      1: { "count": 2001 }, 
      2: { "count": 579 },
      3: { "count": 554 } 
    } 
  }
}

...您的减速器可能如下所示:

function reducer(state, action) {

  switch (action.type) {
    case 'FILTER_FLIGHT_OFFERS':
      return {
        ...state,
        entities: {
          ...state.entities,
          searchItems: Object.keys(state.entities.searchItems).reduce((newItems, id) => {
            const oldItem = state.entities.searchItems[id];
            if (oldItem.type === action.groupType) {
              newItems[id] = { ...oldItem, checked: id === action.id };
            } else {
              newItems[id] = oldItem;
            }
            return newItems;
          }, {})
        }
      };
  }

  return state;
}

如果您使用 combineReducers 并为您的 searchItems 创建一个缩减器,这会变得更简单。而且 lodash 还可以简化事情:

import mapValues from 'lodash/mapValues';

function searchItemsReducer(state, action) {

  switch (action.type) {
    case 'FILTER_FLIGHT_OFFERS':
      return mapValues(state, (oldItem, id) => (
        oldItem.type === action.groupType 
          ? { ...oldItem, checked: id === action.id };
          : oldItem
      ));
  }

  return state;
}