我正在尝试找出更新状态树上的几个顶级字段的理想方法,同时仍然维护拆分减速器。
这是我想出的一个简单的解决方案。
var state = {
fileOrder: [0],
files: {
0:{
id: 0,
name: 'asdf'
}
}
};
function handleAddFile(state, action) {
return {...state, ...{[action.id]:{id: action.id, name: action.name}}};
};
function addFileOrder(state, action) {
return [...state, action.id];
}
// Adding a file should create a new file, and add its id to the fileOrder array.
function addFile(state, action) {
let id = Math.max.apply(this, Object.keys(state.files)) + 1;
return {
...state,
fileOrder: addFileOrder(state.fileOrder, {id}),
files: handleAddFile(state.files, {id, name: action.name})
};
}
目前我可以发送单个操作{type: ADD_FILE, fileName: 'x'}
, then addFile
在内部创建一个动作发送到addFileOrder
and addFile
.
我很好奇这是否被认为是执行以下任一操作的更好方法。
相反,分派两个操作,一个用于添加文件,然后获取它的 id 并分派一个ADD_TO_FILE_ORDER
使用 id 进行操作。
或火灾和行动,如{type: ADD_FILE, name: 'x', id: 1}
,而不是允许addFile
计算新的 id。这将允许我使用combineReducers
并根据操作类型进行过滤。
这个例子可能很简单,但我的实际状态树有点复杂,添加的每个文件也需要添加到其他实体。
对于一些额外的上下文,更完整的状态树将如下所示。
{
"fileOrder": [0]
"entities": {
"files": {
0: {
id: 0,
name: 'hand.png'
}
},
"animations": {
0: {
id: 0,
name: "Base",
frames: [0]
}
},
"frames": {
0: {
id: 0,
duration: 500,
fileFrames: [0]
}
},
"fileFrames": {
0: {
id: 0,
file: 0,
top: 0,
left: 0,
visible: true
}
}
}
}
添加文件需要:
- 将其添加到文件哈希中。
- 将其添加到 fileOrder 数组中。
- 为每个框架添加一个引用文件的 fileFrame。
- 将每个新的 fileFrame 添加到为其创建的框架中。
最后两点让我想知道我是否能够使用combineReducers。