我正在使用normalizr
来组织我的redux
- 商店状态。
假设我已将Todo-list标准化:
{
result: [1, 2],
entities: {
todo: {
1: {
id: 1,
title: 'Do something'
},
2: {
id: 2,
title: 'Second todo'
}
}
}
}
然后我想实施addTodo
行动。我需要在todo对象中有一个id,所以我生成一个随机的:
function todoReducer(state, action) {
if(action.type == ADD_TODO) {
const todoId = generateUUID();
return {
result: [...state.result, todoId],
enitities: {
todos: {
...state.entities.todos,
[todoId]: action.todo
}
}
}
}
//...other handlers...
return state;
}
但问题是最终所有数据都将保存到服务器,生成的id应该替换为真实服务器分配的id。现在我合并它们:
//somewhere in reducer...
if(action.type === REPLACE_TODO) {
// copy todos map, add new entity, remove old
const todos = {
...state.entities.todos
[action.todo.id]: action.todo
};
delete todos[action.oldId];
// update results array as well
const result = state.result.filter(id => id !== oldId).concat(action.todo.id);
// return new state
return {entities: {todos}, result};
}
这似乎是一个有效的解决方案,但也有很多开销。您知道如何简化此操作并且不进行REPLACE_TODO
操作吗?