공부기록/[강의노트] Udemy React 완벽가이드 201~300

# 248 [udemy React 완벽 가이드 노트] action에 페이로드(추가속성) 연결하기

Jenner 2022. 10. 12. 22:38

 

 

지금까지는 간단한 actions만 reducer function에 보냈다.

action 객체에는 type만 있었다. 

 

 

다른 값을 전달해보자. 


 

Counter 컴포넌트에서 한번 누를 때마다

5씩 증가하는 버튼을 만들어보자. 

 

 

store 폴더의 index.js 파일 (reducer function 과 createStore가 있는 파일)

const counterReducer = (state = { counter: 0 }, action) => {
  if (action.type === "increment") {
    return { counter: state.counter + 1 };
  }

  if (action.type === "decrement") {
    return { counter: state.counter - 1 };
  }

  if (action.type === "increase5") {
    return {
      counter: state.counter + 5,
    };
  }

 

위와 같이 action.type을 한 개 더 만들어 counter 를 state.counter +5 로 증가시키자. 

이렇게 하드코딩 한다면 

사용자 입력값으로 작업해야 할 경우,

즉, +5가 아닌 +??? 몇이 올지 모를 때를 

대비한 코드를 작성 할 수 없다. 

 

 

그렇게 하려면 

 

 if (action.type === "increase") {
    return {
      counter: state.counter + action.amount,
    };
  }

숫자 고정값이 아닌 action.value로 해준다면 

어떤 값이든 받아서 반영할 수 있게 된다. 

 

 

Counter컴포넌트로 가서 

  const increaseHandler = () => {
    dispatch({ type: "increase", amount: 5 });
  };

작성해준 뒤, 5씩 증가하는 버튼에 연결해 주면

5씩 증가하게 된다. 

여기서도 amount의 값은 하드코딩 되어있지만, 

나중에는 input에서 받아서 넣어줄 수 있게 될 것이다. 

 

 

action.amount와  dispatch에 전달해준 amount는 같은 이름이어야 

데이터가 전달되는 데 성공할 것이다.