javascript - 为什么要在减速机中使用开关盒?
问题描述
我想知道在 reducer 中使用 switch case 语法而不是对象映射语法有什么好处?我还没有遇到任何使用 switch case 以外的语句的示例,我想知道为什么没有替代方案。请描述您对这两种方式的优缺点的看法(仅在合理的情况下)。
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
}
}
解决方案
除了它们是惯用的/标准化的并且可以帮助其他人理解您的代码之外,reducers 中的 switch 语句(据我所知)没有任何优势。
就个人而言,我已经切换到非开关减速器。
推荐阅读
- java - 单线从另一个列表初始化列表
- wordpress - Wordpress 表单操作不适用于 AMP
- java - 如何使用 Liquibase 3.5 for MSSQL 将“GETDATE()”字符串输出到带有 loadData 更改的字符串列?
- ios - 检查 JB 的应用程序会被拒绝吗?
- excel - 在vba公式中使用未知范围的单元格
- sql-server - SSMS - 无法使用本地计算机上的 SSMS 连接到 Azure VM 上的 SQL Server 2017 Express
- java - 使用 Elastic Beanstalk Tomcat 启用垃圾收集日志记录
- python - 使用布尔或序列对象(高级索引)获取 numpy 数组的视图
- python - Twisted Python IRC bot - 如何异步执行函数以使其不会阻塞机器人?
- java - 如何使用 Spring Boot Webflux 打包 ReactJs 应用程序