减少样板代码在redux中关于 reduce重构的应用
原始代码
// 省略了内容 function updateObject(oldObject, newValues) {} function updateItemInArray(array, itemId, updateItemCallback) {} function setVisibilityFilter(visibilityState, action) { // 从技术上将,我们甚至不关心之前的状态 return action.filter; } function visibilityReducer(visibilityState = 'SHOW_ALL', action) { switch(action.type) { case 'SET_VISIBILITY_FILTER' : return setVisibilityFilter(visibilityState, action); default : return visibilityState; } }; function addTodo(todosState, action) { const newTodos = todosState.concat({ id: action.id, text: action.text, completed: false }); return newTodos; } function toggleTodo(todosState, action) { const newTodos = updateItemInArray(todosState, action.id, todo => { return updateObject(todo, {completed : !todo.completed}); }); return newTodos; } function editTodo(todosState, action) { const newTodos = updateItemInArray(todosState, action.id, todo => { return updateObject(todo, {text : action.text}); }); return newTodos; } function todosReducer(todosState = [], action) { switch(action.type) { case 'ADD_TODO' : return addTodo(todosState, action); case 'TOGGLE_TODO' : return toggleTodo(todosState, action); case 'EDIT_TODO' : return editTodo(todosState, action); default : return todosState; } } function appReducer(state = initialState, action) { return { todos : todosReducer(state.todos, action), visibilityFilter : visibilityReducer(state.visibilityFilter, action) }; }
使用样板代码后不在需要switch语句,有些代码洁癖很讨厌使用if和switch的条件判断,使用样板代码后可以使得代码可以配置
// 省略了内容 function updateObject(oldObject, newValues) {} function updateItemInArray(array, itemId, updateItemCallback) {} function createReducer(initialState, handlers) { return function reducer(state = initialState, action) { if (handlers.hasOwnProperty(action.type)) { return handlers[action.type](state, action) } else { return state } } } // 省略了内容 function setVisibilityFilter(visibilityState, action) {} const visibilityReducer = createReducer('SHOW_ALL', { 'SET_VISIBILITY_FILTER' : setVisibilityFilter }); // 省略了内容 function addTodo(todosState, action) {} function toggleTodo(todosState, action) {} function editTodo(todosState, action) {} const todosReducer = createReducer([], { 'ADD_TODO' : addTodo, 'TOGGLE_TODO' : toggleTodo, 'EDIT_TODO' : editTodo }); function appReducer(state = initialState, action) { return { todos : todosReducer(state.todos, action), visibilityFilter : visibilityReducer(state.visibilityFilter, action) }; }
相关推荐
weiqi 2020-01-10
范群松 2020-08-02
Unimen 2020-06-21
与您共享 2020-06-17
washing 2020-06-16
肖舸NoSQLt架构 2020-06-12
saradx 2020-06-09
gtsjx 2020-05-19
LazySleep 2020-05-11
zhouhaihua00 2020-05-05
gougouzhang 2020-04-18
JimyFengqi 2020-03-08
liangzuojiayi 2020-03-04
zuihaobushi 2020-03-03
qidu 2020-03-01
ChaITSimpleLove 2020-01-09
pxy 2020-01-08
jadamouse 2019-12-17