Front-End

vsoghlv@naver.com

React.js 리덕스 기본 모듈 만들기

리덕스 모듈이란 액션 타입, 액션 생성 함수, 리듀서가 모두 들어있는 자바스크립트 파일을 말한다. 세가지다 모두 다른 파일에 작성해도 된다.

하지만 보통 한번에 작성하는 것을 권장하는데 이를 Ducks 패턴이라고 한다.

리듀서는 export default 로 액션 생성 함수는 export 로 내보내준다.

리덕스를 이용해 ToDo 를 구현해볼 건데 먼저 counter 모듈을 만들어보자

//counter.js
const SET_DIFF = "counter/SET_DIFF";

Ducks 패턴을 사용할 때는 액션 타입을 선언할 때 위와 같이 접두사를 붙이는데 다른 모듈과 이름이 중복되지 않게 하기 위함이다.

//modules/counter.js
//액션 타입
const SET_DIFF = "counter/SET_DIFF"; //숫자를 얼마씩 변경할지
const INCREASE = "counter/INCREASE";
const DECREASE = "counter/DECREASE";

//액션 생성 함수
export const setDiff = (diff) => ({ type: SET_DIFF, diff });
export const increase = () => ({ type: INCREASE });
export const decrease = () => ({ type: DECREASE });

//초기상태
const initialState = {
  number: 0,
  diff: 1,
};

//리듀서
export default function counter(state = initialState, action) {
  switch (action.type) {
    case SET_DIFF:
      return {
        ...state,
        diff: action.diff,
      };
    case INCREASE:
      return {
        ...state,
        number: state.number + state.diff,
      };
    case DECREASE:
      return {
        ...state,
        number: state.number + state.diff,
      };
    default:
      return state;
  }
}

//modules/todos.js
//액션 타입
const ADD_TODO = "todos/ADD_TODO";
const TOGGLE_TODO = "todos/TOGGLE_TODO";

let nextId = 1;

//액션 생성 함수
export const addTodo = (text) => ({
  type: ADD_TODO,
  todo: {
    id: nextId++,
    text,
  },
});
export const toggleTodo = (id) => ({
  type: TOGGLE_TODO,
  id,
});

//초기상태
const initialState = [
  /*
    {
        id: 1,
        text:'ex',
        done:false
    }
  */
];

//리듀서
export default function todos(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return state.concat(action.todo);
    case TOGGLE_TODO:
      return state.map((todo) =>
        todo.id === action.id ? { ...todo, done: !todo.done } : todo
      );
    default:
      return state;
  }
}

두개의 리듀서가 완성됐는데 이런 경우 하나로 합치기 위해 root 리듀서를 만들어 주는데 이때는

import { combineReducers } from "redux";

를 불러와 사용해준다. 불러온 후 combineReducer 에 만든 두개의 리듀서를 넣어주면 된다.

//modules/index.js
import { combineReducers } from "redux";
import counter from "./counter";
import todos from "./todos";

const rootReducer = combineReducers({ counter, todos });

export default rootReducer;

이제 두개의 리덕스 모듈과 리듀서 두개를 합친 루트 리듀서를 만들었다. 이제 리액트에서 적용하기위해 패키지 하나를 설치해야 한다.

yarn add react-redux

이제 기존의 index.js 에서 Provider 을 불러와 주면 된다.(modules 폴더에 만든 index.js 파일이 아니다.)

그리고 store 을 만들기 위해 createStorerootReducer 을 불러오자

//index.js
import { Provider } from "react-redux";
import { createStore } from "redux";
//./modules 만 불러와도 된다.
import rootReducer from "./modules";

const store = createStore(rootReducer);

이제 리액트에서 리덕스를 적용해보자. 방법은 간단하다. App 컴포넌트를 Provider 로 감싸주고 props 로 store 을 보내주면 된다.

//index.js
<Provider store={store}>
  <App />
</Provider>