首页 > 解决方案 > 为什么要在减速机中使用开关盒?

问题描述

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

标签: javascriptreactjsredux

解决方案


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

就个人而言,我已经切换到非开关减速器。


推荐阅读