javascript-为什么在减速器中使用开关盒?

前端之家收集整理的这篇文章主要介绍了javascript-为什么在减速器中使用开关盒? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想知道在reducer中而不是例如使用switch case语法有什么好处对象映射语法?
除了切换用例,我还没有遇到任何使用其他语句的示例,我想知道为什么没有其他选择.
请描述您对两种方式的优缺点的想法(仅在有正当理由的情况下).

  1. const initialState = {
  2. visibilityFilter: 'SHOW_ALL',todos: []
  3. };
  4. // object mapping Syntax
  5. function reducer(state = initialState,action){
  6. const mapping = {
  7. SET_VISIBILITY_FILTER: (state,action) => Object.assign({},state,{
  8. visibilityFilter: action.filter
  9. }),ADD_TODO: (state,{
  10. todos: state.todos.concat({
  11. id: action.id,text: action.text,completed: false
  12. })
  13. }),TOGGLE_TODO: (state,{
  14. todos: state.todos.map(todo => {
  15. if (todo.id !== action.id) {
  16. return todo
  17. }
  18. return Object.assign({},todo,{
  19. completed: !todo.completed
  20. })
  21. })
  22. }),EDIT_TODO: (state,{
  23. text: action.text
  24. })
  25. })
  26. })
  27. };
  28. return mapping[action.type] ? mapping[action.type](state,action) : state
  29. }
  30. // switch case Syntax
  31. function appReducer(state = initialState,action) {
  32. switch (action.type) {
  33. case 'SET_VISIBILITY_FILTER': {
  34. return Object.assign({},{
  35. visibilityFilter: action.filter
  36. })
  37. }
  38. case 'ADD_TODO': {
  39. return Object.assign({},{
  40. todos: state.todos.concat({
  41. id: action.id,completed: false
  42. })
  43. })
  44. }
  45. case 'TOGGLE_TODO': {
  46. return Object.assign({},{
  47. todos: state.todos.map(todo => {
  48. if (todo.id !== action.id) {
  49. return todo
  50. }
  51. return Object.assign({},{
  52. completed: !todo.completed
  53. })
  54. })
  55. })
  56. }
  57. case 'EDIT_TODO': {
  58. return Object.assign({},{
  59. text: action.text
  60. })
  61. })
  62. })
  63. }
  64. default:
  65. return state
  66. }
  67. }
最佳答案
在缩减程序中(我知道),switch语句没有任何优势,除了它们是惯用的/标准化的,而且可以帮助其他人理解您的代码.

就个人而言,我已切换到非切换减速器.

猜你在找的JavaScript相关文章