在 react redux doc todo 示例中,Dan 将类型为 TOGGLE_TODO
的操作传递给 todos
,然后将其传递给每个单独的 todo。我注意到他的逻辑是检查 todo.id
是否在 todo
reducer 中。不能在 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
最佳答案
我认为你是对的,如果你看一下 todomvc example从 redux 源代码存储库中,您只会看到一个 todos
reducer。
文档可能有点过时,或者此类嵌套 reducer 可能只是其可能性的一个示例。
关于javascript - 在父 reducer 与子 reducer 中完成的 React redux 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39196763/