在react redux doc todo示例中,Dan将类型为TOGGLE_TODO
的 Action 传递给todos
,然后将其传递给每个单独的待办事项。我注意到他的逻辑正在检查todo.id
简化器中的todo
。这个逻辑也不能在todos
中完成吗?对我而言,在您遍历每个待办事项而不是将工作传递给每个待办事项并让他们弄清楚是否需要切换时,最好在更高层次上照顾逻辑。 Dan这样做有理由吗?
const todo = (state = {}, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
}
case 'TOGGLE_TODO':
if (state.id !== action.id) {
return state
}
return Object.assign({}, state, {
completed: !state.completed
})
default:
return state
}
}
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
]
case 'TOGGLE_TODO':
return state.map(t =>
todo(t, action)
)
default:
return state
}
}
export default todos
最佳答案
我认为您是对的,如果您从redux源代码存储库看todomvc example,您只会看到一个todos
reducer。
这些文档可能有些过时,或者这样的嵌套化简可能只是其可能性的一个示例。