将字符串传递给 Redux 存储以触发操作而不是简单地在存储上指定其他方法并直接调用这些方法有什么好处?似乎后者可以让人们避免一堆if
orswitch
语句。例如,来自 Redux 文档:
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
{
text: action.text,
completed: false
}
]
case 'COMPLETE_TODO':
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: true
})
}
return todo
})
default:
return state
}
}
替代:
const todos = {
addTodo: function(state, action) {
return [
...state,
{
text: action.text,
completed: false
}
]
},
completeTodo: function(state, action) {
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: true
})
}
return todo
})
}
}