Redux 공식 홈페이지 따라하기
Redux 따라 만들어보기 (4) - 리팩토링
vitamin3000
2025. 1. 28. 21:39
이번 포스트에서는 지난 (3) 포스트에서 작성한 코드를 세분화하려 한다.
redux.js
이 파일에는 redux에서 제공하는 기능들을 작성하였다.
export function actionCreator(type, payload) {
return {
type,
payload
}
}
export function createStore(reducer) {
let state;
let handlers = [];
function dispatch(action) {
state = reducer(state, action);
handlers.forEach(handler => handler());
}
function subscribe(handler){
handlers.push(handler)
}
function getState() {
return state;
}
return {
dispatch,
getState,
subscribe
};
}
매개변수 값으로 type 뿐만아니라 payload의 데이터 형태도 들어옴에 주의하라
이렇게 받은 payload 값을 ...
reducer.js에서 사용할 수 있다.
export function reducer(state = {count: 0}, action ) {
if (action.type === 'increase')
{
// if(action.payload)
return { ...state, count: state.count+1}
}
else if (action.type === 'decrease')
{
return { ...state, count: state.count-1};
}
else {
return { ...state};
}
}
redux에는 action에 해당 state의 값을 담아 보낸다고 했는데..
그럼 다음과 같이 actions.js를 작성할 수 있다.
import { INCREASE, DECREASE } from "./action-type";
import { actionCreator } from "./redux";
export const increase = () => {
return actionCreator(INCREASE);
}
export const decrease = () => {
return actionCreator(DECREASE);
}
app.js에서 사용할 떄는 ..
import { createStore, actionCreator } from "./redux";
import { reducer } from "./reducer";
import { decrease, increase } from './actions'
const store = createStore(reducer);
store.subscribe(function() {
store.getState();
});
store.dispatch(increase())
store.dispatch(decrease())
이번에는 Currying기법을 활용하여 redux안의 코드를 변경해보고자 한다.
*Currying : 함수의 인자가 여러개 있을 때 각각의 인자를 할당하는 여러 개의 내부 함수로 쪼개는 것
redux.js
export const actionCreator = type => payload = { type, payload }
actions.js
export const increase = actionCreator(INCREASE);
Curry로 변환하지 않으면,
app.js에서 사용할 때
store.dispatch(increase())
store.dispatch(decrease())
increase나 decrease 안에 payload를 넘기고 싶을 때 데이터를 넘길 수 없다
왜냐하면 하나의 인자로 처리하고 있었기 때문이다.
action.js에서 type만 넘기고 'type'을 갖고 있는 actionCreator 함수를 increase에 넘기기 때문에 아직 increase는 함수이다
따라서 dispatch마다 값을 넣을 수 있게 되는 것이다.
이것을 호출 지연이라 한다.
Curry에 대해 학습해봐야겠다