我正试图在redux存储中存储一组数据,这些数据由id
字段散列。
我的减速器看起来像:
// The initial state of the App
export const initialState = {
events: {},
loading: false,
saving: false,
error: false
};
const eventReducer = (state = initialState, action) =>
produce(state, draft => {
switch (action.type) {
case LOAD_EVENT:
draft.loading = true;
draft.error = false;
break;
case LOAD_EVENT_SUCCESS:
draft.loading = false;
draft.events = {
...state.events,
[action.id]: action.event
};
break;
case LOAD_EVENT_ERROR:
draft.loading = false;
draft.error = action.error;
break;
case LOAD_PENDING:
draft.loading = true;
draft.error = false;
break;
case LOAD_PENDING_SUCCESS:
draft.loading = false;
draft.events = {
...state.events,
...action.events.map(entry => {
return { [entry['id']]: entry };
})
};
break;
case LOAD_PENDING_ERROR:
draft.error = action.error;
draft.loading = false;
break;
case LOAD_UPCOMING:
draft.loading = true;
draft.error = false;
break;
case LOAD_UPCOMING_SUCCESS:
draft.loading = false;
draft.events = {
...state.events,
...action.events.map(entry => {
return { [entry['id']]: entry };
})
};
break;
case LOAD_UPCOMING_ERROR:
draft.error = action.error;
draft.loading = false;
break;
case LOAD_PREVIOUS:
draft.loading = true;
draft.error = false;
break;
case LOAD_PREVIOUS_SUCCESS:
draft.loading = false;
draft.events = {
...state.events,
...action.events.map(entry => {
return { [entry['id']]: entry };
})
};
break;
case LOAD_PREVIOUS_ERROR:
draft.error = action.error;
draft.loading = false;
break;
}
});
其中action.event
看起来像{id: 12, name: 'Test', ...}
,而action.events
将是像[{id: 12, name: 'Test', ...}, {id: 15, name: 'Another test', ...}]
的阵列。
但是,当由于LOAD_PENDING_SUCCESS
操作成功而加载events
时,状态为:{events: {0: {12, {id: 12, name: 'Test', ...}}}, {1: {15: {id: 15, name: 'Another test', ...}}}}
我希望我的events
以事件id为键,所以当我执行= {...events, ...newEvents}
时,如果状态对象的events属性具有与newEvents中的记录相同的id
的数据,则事件对象将被newEvents的条目替换。
您可以这样尝试:
case LOAD_PENDING_SUCCESS:
draft.loading = false;
draft.events = {
...state.events,
...action.events.reduce((acc, val) => {
return { ...acc, [val.id]: val };
}, {})
};
break;
或者,对于数据的规范化,您可以使用normalizer库。它非常有用。