我正在使用带有不可变的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):
知道为什么会发生这种行为吗?
答案 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
函数的一些错误。