我正在使用 normalizr
来组织我的 redux
-store状态 .
假设我已经规范化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
操作吗?