들어가기
이전 글에서 + 버튼과 - 버튼을 눌러 1씩 증감하는 카운터를 만들었다.
매우 단순하게 하나의 action을 다뤘는데, 지금부터는 아주 약간 더 다양한 것을 하려고 한다.
예를 들어 1가 아니라 5씩 증가하는 버튼이나, 카운터 버튼이 보였다/보이지 않는 토글 같은 것은 어떻게 만들 수 있을까?
payload
먼저 5씩 증가하는 버튼을 만들고 싶다면 어떻게 해야 할까?
if (action.type === '5 plus') {
return {
counter: state.counter + 5,
};
}
물론 이렇게 해도 상관 없지만, 이는 확장성이 떨어진다.
action에 원하는 속성을 추가하는 더 좋은 방법이 있다.
action은 객체라는 점을 기억하고 가자.
const morePlusHandler = () => {
dispatch({ type: 'plus5', amount: 5 });
};
이런 함수를 만들고 +5 라는 button에 onClick 이벤트로 바인딩 해주었다.
action의 type은 plus5, action의 amount는 5인 객체를 dispatch하겠다.
if (action.type === 'plus5') {
return {
counter: state.counter + action.amount,
};
}
말한대로 적어주면 끝!
action의 type이 plus5일 때, counter는 기존 state.counter에 action의 amount인 5를 더해준다.
3번 누르니 15가 나왔고 +와 - 버튼을 눌러도 정상적으로 1씩 증감하는 것을 확인할 수 있다.
다중 state 작업
카운터 버튼이 보였다/보이지 않는 토글 역할을 하는 버튼을 만들어보겠다.
토글은 useState로도 관리할 수 있지만 다중 state로도 작업하는 방법을 배워보자.
<div>
<button onClick={plusHandler}>+</button>
<button onClick={minusHandler}>-</button>
<button onClick={morePlusHandler}>+5</button>
</div>
<button onClick={toggleHandler}>Toggle</button>
이렇게 버튼들이 있을 때 toggleHandler에 따라서 상위 div가 보여졌다 보이지 않게 되어야 한다.
보여졌다 보이지 않게 되는, boolean 상태를 새로 Redux store에 추가해주어야 한다.
const counterReducer = (state = { counter: 0, showCounter: true }, action) => {
이런 식으로 state에 counter와 showCounter를 할당해주었다.
그런데 이렇게 하면 state가 길어서 가독성이 좋지 않으니까 좀 더 간단하게 상수로 빼내주자.
const initialState = { counter: 0, showCounter: true };
const counterReducer = (state = initialState, action) => {
이제 Toggle 버튼을 누를 때 boolean 값을 바꿔주려고 하는데, 그 전에 다른 버튼들을 누를 때의 변경을 수정해주어야 한다.
plus, minus, plus5를 눌렀을 때는 counter 값만 바뀌고 showCounter는 그대로 유지되어야 한다.
const counterReducer = (state = initialState, action) => {
if (action.type === 'plus') {
return {
counter: state.counter + 1,
};
}
if (action.type === 'minus') {
return {
counter: state.counter - 1,
};
}
if (action.type === 'plus5') {
return {
counter: state.counter + action.amount,
};
}
return state;
};
그래서 이랬는데
const counterReducer = (state = initialState, action) => {
if (action.type === 'plus') {
return {
counter: state.counter + 1,
showCounter: state.showCounter,
};
}
if (action.type === 'minus') {
return {
counter: state.counter - 1,
showCounter: state.showCounter,
};
}
if (action.type === 'plus5') {
return {
counter: state.counter + 5,
showCounter: state.showCounter,
};
}
if (action.type === 'toggle') {
return {
counter: state.counter,
showCounter: !state.showCounter,
};
}
이래 됐습니다 :)
이렇게 리듀서 함수를 수정했다면 이제 핸들러에서 액션을 디스패치 할 수 있도록 수정해주어야 한다.
const showCounter = useSelector(state => state.showCounter);
const toggleHandler = () => {
dispatch({ type: 'toggle' });
};
위와 같이 useSelector로 showCounter에 접근하고, action의 type이 toggle일 때 데이터가 변하도록 dispatch한다.
그리고 위에서 button들이 있던 div를 아래와 같이 조건부로 보여주게 코드를 수정한다.
{showCounter && (
<div>
<button onClick={plusHandler}>+</button>
<button onClick={minusHandler}>-</button>
<button onClick={morePlusHandler}>+5</button>
</div>
)}
위와 같이 Toggle을 누를 때마다 카운터 버튼들이 사라졌다 나타나는 것을 확인할 수 있다.
Redux는 잘 안 써봤는데 재미있구만...
'⚛️ React > ✨ Redux' 카테고리의 다른 글
[Redux] Redux-toolkit 알아보기 (0) | 2024.04.14 |
---|---|
[Redux] useSelector, useDispatch로 상태 업데이트 하기 (0) | 2024.04.12 |
[Redux] Redux 알아보기 (1) | 2024.03.31 |