mingg IT

[React] redux-action 사용하기 (typeScript) 본문

FrontEnd

[React] redux-action 사용하기 (typeScript)

mingg123 2021. 11. 30. 13:30

리덕스를 좀 더 편하게 사용하는 방법이다. redux-actions를 사용하면 액션 생성 함수를 훨씬 짧고 가독성 좋은 함수로 만들수 있다.

 

1. yarn add redux-actions 

typeScript를 사용할 경우에는 (npm i --save-dev @types/redux-actions)

 

2. 사용전 코드

export const changeInput = (input: String) => ({
  type: CHANGE_INPUT,
  input,
});


function search(state = initialState, action: any) {
  switch (action.type) {
    case CHANGE_INPUT:
      return {
        ...state,
        input: action.input,
      };
    default:
      return state;
  }
}

 

3. 사용 후 코드

import { createAction, handleActions } from "redux-actions";
export const changeInput = createAction(CHANGE_INPUT, (input: String) => input);

const search = handleActions(
  {
    [CHANGE_INPUT]: (state, { payload }) => ({
      ...state,
      input: payload.input,
    }),
  },
  initialState
);

 

search 함수가 훨신 짧아졌다. 지금은 예시가 1개 뿐이지만 사용전 코드에서는 switch, case를 쓰며 주렁주렁 길어지지만 지금은 훨씬더 짧고 가독성 있게 바꿀 수 있다. 

Comments