gpt4 book ai didi

javascript - 为什么在reducer中使用switch case?

转载 作者:行者123 更新时间:2023-11-29 10:56:42 25 4
gpt4 key购买 nike

我想知道在 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
}
}

最佳答案

reducer 中的 switch 语句(据我所知)没有任何优势,除了它们是惯用的/标准化的并且可以帮助其他人理解您的代码。

就我个人而言,我已改用非开关 reducer 。

关于javascript - 为什么在reducer中使用switch case?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55787266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com