리덕스 파일 작성법

리린·2021년 7월 25일
0

React

목록 보기
9/47

src/modules 폴더 생성

각 모듈별로 다음과 같이 작성

  • 액션 타입
const INCREASE = 'counter/INCREASE';
const DECREASE = 'counter/DECREASE';
  • 액션 생성 함수

export const increase = () => ({
  type: INCREASE,
});
export const decrease = () => ({
  type: DECREASE,
});
  • 리듀서 함수 + 초기값

const initialState = {
  number: 0,
};

function counter(state = initialState, action) {
  switch (action.type) {
    case INCREASE:
      return {
        number: state.number + 1,
      };
    case DECREASE:
      return {
        number: state.number - 1,
      };
    default:
      return state;
  }
}

export default counter;

export default vs export

  • export default
    하나만 가능
    {}없이 import함

  • export
    여러 개 가능
    {}로 import할 수 있음

루트 리듀서 만들기

  • combineReducers 유틸 함수 사용하기
  • 코드
    (index.js)
import { combineReducers } from 'redux';
import counter from './counter';
import todos from 'todos';

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

export default rootReducer;
profile
개발자지망생

0개의 댓글