我想知道在reducer中使用switch case语法而不是例如e.g对象映射语法? 除了切换用例,我还没有遇到任何使用其他语句的示例,我想知道为什么没有其他选择。 请描述您对两种方式的优缺点的想法(仅在有正当理由的情况下)。
const initialState = {
visibilityFilter: 'SHOW_ALL',
todos: []
};
// object mapping syntax
function reducer(state = initialState, action){
const mapping = {
SET_VISIBILITY_FILTER: (state, action) => Object.assign({}, state, {
visibilityFilter: action.filter
}),
ADD_TODO: (state, action) => Object.assign({}, state, {
todos: state.todos.concat({
id: action.id,
text: action.text,
completed: false
})
}),
TOGGLE_TODO: (state, action) => Object.assign({}, state, {
todos: state.todos.map(todo => {
if (todo.id !== action.id) {
return todo
}
return Object.assign({}, todo, {
completed: !todo.completed
})
})
}),
EDIT_TODO: (state, action) => Object.assign({}, state, {
todos: state.todos.map(todo => {
if (todo.id !== action.id) {
return todo
}
return Object.assign({}, todo, {
text: action.text
})
})
})
};
return mapping[action.type] ? mapping[action.type](state, action) : state
}
// switch case syntax
function appReducer(state = initialState, action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER': {
return Object.assign({}, state, {
visibilityFilter: action.filter
})
}
case 'ADD_TODO': {
return Object.assign({}, state, {
todos: state.todos.concat({
id: action.id,
text: action.text,
completed: false
})
})
}
case 'TOGGLE_TODO': {
return Object.assign({}, state, {
todos: state.todos.map(todo => {
if (todo.id !== action.id) {
return todo
}
return Object.assign({}, todo, {
completed: !todo.completed
})
})
})
}
case 'EDIT_TODO': {
return Object.assign({}, state, {
todos: state.todos.map(todo => {
if (todo.id !== action.id) {
return todo
}
return Object.assign({}, todo, {
text: action.text
})
})
})
}
default:
return state
}
}
答案 0 :(得分:2)
Reduce中的switch语句没有惯用的/标准化的优点,它可以帮助其他人理解您的代码。
我个人已经切换到非切换式减速器。