글
React Reducer 관리
R/React
2017. 8. 17. 06:11
AS
import _ from 'lodash'; import { FETCH_READY_COMMENT, FETCH_COMMENT_SUCCESS, FETCH_COMMENT_ERROR, ADD_READY_COMMENT, ADD_COMMENT_SUCCESS, ADD_COMMENT_ERROR } from './CommentActions'; const initialState = { comments: [], }; const CommentReducer = (state = initialState, action) => { switch(action.type) { case ADD_READY_COMMENT: return { ...state, comments: [...state.comments, action.comment] }; case ADD_COMMENT_SUCCESS: return { ...state, comments: _.map(state.comments, comment => (comment.id === action.id ? { ...comment, id: action.newId } : comment)) }; case ADD_COMMENT_ERROR: default: return state; } }; export default CommentReducer;TO BE
... const addCommentReducer = { [ADD_READY_COMMENT]: (state, action) => ({ ...state, comments: [...state.comments, action.comment] }), [ADD_COMMENT_SUCCESS]: (state, action) => ({ ...state, comments: _.map(state.comments, comment => (comment.id === action.id ? { ...comment, id: action.newId } : comment)) }), [ADD_COMMENT_ERROR]: (state, action) => ({ ...state, comments: _.filter(state.comments, comment => (comment.id !== action.id)) }) }; function createReducer(initialState, handlers) { return function reducer(state = initialState, action) { if (handlers.hasOwnProperty(action.type)) { return handlers[action.type](state, action); } else { return state; } }; } const CommentReducer = createReducer(initialState, { ...addCommentReducer, }); export default CommentReducer;- createReducer 메소드를 하나 만들어 switch 문이 아닌 객체 속성으로 액션타입에 맞는 리듀서를 찾는다. http://redux.js.org/docs/recipes/ReducingBoilerplate.html#generating-reducers
- 타입별 묶음으로 관리하면 리듀서 구분이 쉬워진다.
'R > React' 카테고리의 다른 글
React Heroku 초기 세팅. (0) | 2017.07.28 |
---|