All files / src/chap07 HookReducerUp.js

0% Statements 0/12
0% Branches 0/3
0% Functions 0/5
0% Lines 0/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                                                                     
import { useReducer } from 'react';
 
export default function HookReducerUp({ init }) {
  const [state, dispatch] = useReducer(
    (state, action) => {
      switch (action.type) {
        // 카운트 값의 증감
        case 'update':
          return { count: state.count + action.step };
        // 카운트 값 초기화
        case 'reset' :
          return { count: action.init };
        // 기본 동작(State를 그대로 반환)
        default:
          return state;
      }
    },
    {
        count: init
    }
  );
  // 각 버튼에 대응하는 핸들러
  const handleUp = () => dispatch({ type: 'update', step: 1 });
  const handleDown = () => dispatch({ type: 'update', step: -1 });
  const handleReset = () => dispatch({ type: 'reset', init: 0 });
 
  return (
  <>
    <button onClick={handleUp}>카운트업</button>
    <button onClick={handleDown}>카운트다운</button>
    <button onClick={handleReset}>리셋</button>
    <p>{state.count}번 클릭되었습니다.</p>
  </>
  );
}