在這個減速機組成的例子中,爲什麼我們不能只返回我們正在調用的減速機?意思是在todoApp
減速機的情況下ADD_TODO
或TOGGLE_TODO
我們使用的是其他減速機:todos
。我明白那個。但我不明白爲什麼我們不能只是設置的情況下在todoApp
作爲Reducer組成 - 爲什麼我們需要重新分配todos與Object.assign()爲什麼不只是調用其他reducer?
function todoApp(state = initialState, action) {
switch (action.type) {
case ADD_TODO:
case TOGGLE_TODO:
return todos(state.todos, action)
VS我們這裏:
function todoApp(state = initialState, action) {
switch (action.type) {
case ADD_TODO:
case TOGGLE_TODO:
return Object.assign({}, state, {
todos: todos(state.todos, action)
})
特別是自待辦事項減速器返回煥發出新的狀態對象, 對?我們是不是仍然遵循redux規則,而不是通過返回第二個reducer的結果來修改狀態?
function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [
...state,
{
text: action.text,
completed: false
}
]
case TOGGLE_TODO:
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: !todo.completed
})
}
return todo
})
default:
return state
}
}
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
case ADD_TODO:
case TOGGLE_TODO:
return Object.assign({}, state, {
todos: todos(state.todos, action)
})
default:
return state
}
}
所以如果形狀相同,這將是好的,我不會修改狀態,否則,是正確的? – Turnipdabeets
@AnnaGarcia更新了我的答案以解決您的問題 – naomik