用于循环填充具有零索引的空数据点的不可变映射

时间:2017-02-18 01:47:54

标签: angular immutable.js ngrx

我正在使用带有不可变的ngrx存储来处理我的angular 2应用程序中的数据。我有一个reducer将数据从成功的API调用转换为不可变存储的id的映射到对象:sessions: Map<number, ISession>。要从ISession[]中的原生数组action.payload转换,我在withMutations调用中执行foreach循环:

case SessionsActions.LOAD_SESSIONS_SUCCESS:
  return state.withMutations(map => {
    map.set('loading', false);

    action.payload.forEach((session: ISession) => {
      console.log("Setting ",session);
      map.setIn(['sessions', session.id], session );
    });
  }) as ISessions;

我得到了预期的控制台输出,有四个项目:

Setting  Object {id: 6, payslip: null, invlice: null, paidByClient: false, completed: false…}
Setting  Object {id: 8, payslip: null, invlice: 1, paidByClient: true, completed: false…}
Setting  Object {id: 9, payslip: 1, invlice: 1, paidByClient: true, completed: false…}
Setting  Object {id: 7, payslip: null, invlice: null, paidByClient: false, completed: false…}

但是商店里面填充了10个项目,它将id从0填充为空,直到存储数据本身的最大值(9):

enter image description here

知道为什么会发生这种行为吗?

1 个答案:

答案 0 :(得分:0)

我通过手动构建地图并使用set而不是setIn来设置地图来解决问题:

  case SessionsActions.LOAD_SESSIONS_SUCCESS:
  var state = state.withMutations(map => {
    map.set('loading', false);

    var sessions = Map<String, ISession>();
    for (var i = 0; i < action.payload.length; i++)
    {
      var session = action.payload[i];
      sessions = sessions.set(session.id, session );
    }
    map.set('sessions', sessions);
  }) as ISessions;

我认为它是withMutations函数的一些错误。