이전 포스트에서 가정한 내용처럼, 여러 명의 shopkeeper가 각자 맡은 품목만 담당하는 것을 코드로 나타내면 여러 개의 reducer
함수로 표현될 것이다.
우선 하나의 reducer
함수로 여러 개의 액션을 처리하는 예제를 먼저 살펴본다.
const redux = require('redux');
const createStore = redux.createStore;
const BUY_CAKE = 'BUY_CAKE'
// (3) define another action
const BUY_ICECREAM = 'BUY_ICECREAM'
function buyCake() {
return {
type: BUY_CAKE,
info: 'first redux action'
}
}
// (4) define another action creator
function buyIceCream() {
return {
type: BUY_ICECREAM,
}
}
const initialState = {
numOfCakes: 10,
// (1) add another property
numOfIceCreams: 20
}
const reducer = (state = initialState, action) => {
switch(action.type) {
case BUY_CAKE: return {
...state,
numOfCakes: state.numOfCakes - 1
}
// (2) another switch case
case BUY_ICECREAM: return {
...state,
numOfIceCreams: state.numOfIceCreams - 1
}
default: return state
}
}
const store = createStore(reducer);
console.log('Initial State', store.getState());
const unsubscribe = store.subscribe(() => console.log('Updated state', store.getState()))
store.dispatch(buyCake());
store.dispatch(buyCake());
store.dispatch(buyCake());
// (5) dispatch an action
store.dispatch(buyIceCream());
store.dispatch(buyIceCream());
unsubscribe();
Node index
Initial State { numOfCakes: 10, numOfIceCreams: 20 }
Updated state { numOfCakes: 9, numOfIceCreams: 20 }
Updated state { numOfCakes: 8, numOfIceCreams: 20 }
Updated state { numOfCakes: 7, numOfIceCreams: 20 }
Updated state { numOfCakes: 7, numOfIceCreams: 19 }
Updated state { numOfCakes: 7, numOfIceCreams: 18 }
잘 작동하지만 품목이 더 확장된다면reducer
함수가 비대해져 디버깅 및 추적이 어려워질 것이다.
Split our state and reducer.
const redux = require('redux');
const createStore = redux.createStore;
const BUY_CAKE = 'BUY_CAKE'
const BUY_ICECREAM = 'BUY_ICECREAM'
function buyCake() {
return {
type: BUY_CAKE,
info: 'first redux action'
}
}
function buyIceCream() {
return {
type: BUY_ICECREAM,
}
}
// (1) split the initialState into two
const initialCakeState = {
numOfCakes: 10
}
const initialIceCreamState = {
numOfIceCreams: 20
}
// (2) split the reducer into two
const cakeReducer = (state = initialCakeState, action) => {
switch(action.type) {
case BUY_CAKE: return {
...state,
numOfCakes: state.numOfCakes - 1
}
default: return state
}
}
const iceCreamReducer = (state = initialIceCreamState, action) => {
switch(action.type) {
case BUY_ICECREAM: return {
...state,
numOfIceCreams: state.numOfIceCreams - 1
}
default: return state
}
}
const store = createStore(reducer); // problem
The create store method can accept only one reducer. How do we let Redux know about both our reducers?