728x90
728x90
caseReducers (Redux Toolkit) 속성
들어가며
- 리덕스 툴킷(Redux Toolkit)의
caseReducers
속성에 대해 정리해본다. - 이 속성을 이용하면 슬라이스 내의 개별 리듀서 함수에 직접 접근하고 호출할 수 있다.

createSlice() 함수와 caseReducers 속성
createSlice() 함수
- 슬라이스(Slice)를 정의하기 위해 사용된다.
- 슬라이스는 특정 상태(State)와 그 상태를 변경하는 리듀서(Reducer)들을 한 곳에 모아놓은 것이다.
- 슬라이스는 자동으로 액션 생성자(Action Creators)와 액션 타입(Action Types)을 생성해준다.
reducers 옵션
createSlice
함수의reducers
옵션은 슬라이스의 상태를 변경하는 여러 개의 리듀서 함수를 정의하는 객체이다.- 각 키(Key)는 액션 이름에 대응하고, 값(Value)은 해당 액션에 대한 리듀서 함수이다.
caseReducers 속성
- 슬라이스 내에 정의된 각 리듀서 함수에 대한 참조를 포함하는 객체이다.
- 슬라이스 내부에서 다른 리듀서 함수를 직접 호출할 수 있다.
- 모든 상태 변경 후에 총합을 다시 계산해야 하는 경우,
caseReducers
를 사용하면 모든 리듀서에서 동일한 로직을 일관되게 적용할 수 있다. caseReducers
를 사용하면 코드의 재사용성을 높이고, 상태 업데이트의 일관성을 유지시킬 수 있다.- 아래와 같이 사용할 수 있다.
const testSlice = createSlice( name: 'test', initialState, reducers: { action1: (state, action) => { // ... testSlice.caseReducers.action2(state); // ... }, action2: (state, action) => { // ... } } )
예제 코드
- 아래 코드에서
addItem
,editItem
액션은caseReducers
속성을 이용하여calculateTotals
액션을 직접 호출한다.
const cartSlice = createSlice({ name: 'cart', initialState: getCartFromLocalStorage(), reducers: { // 아이템 추가 addItem: (state, action) => { const { product } = action.payload; const item = state.cartItems.find((i) => i.cartID === product.cartID); if (item) { item.amount += product.amount; } else { state.cartItems.push(product); } state.numItemsInCart += product.amount; state.cartTotal += product.price * product.amount; // 다른 리듀서에 직접 접근하여 실행하기 (caseReducers) ✅ cartSlice.caseReducers.calculateTotals(state); toast.success('Item added to cart!'); }, // ... // 아이템 수정하기 editItem: (state, action) => { const { cartID, amount } = action.payload; const item = state.cartItems.find((i) => i.cartID === cartID); state.numItemsInCart += amount - item.amount; state.cartTotal += item.price * (amount - item.amount); item.amount = amount; // 다른 리듀서에 직접 접근하여 실행하기 (caseReducers) ✅ cartSlice.caseReducers.calculateTotals(state); toast.success('Cart updated!'); }, // 총합 구하기 calculateTotals: (state) => { state.tax = 0.1 * state.cartTotal; state.orderTotal = state.cartTotal + state.shipping + state.tax; // 로컬 스토리지에 추가 localStorage.setItem('cart', JSON.stringify(state)); }, }, });
참고 사이트
createSlice | Redux Toolkit
redux-toolkit.js.org
728x90
728x90
'Programming > React' 카테고리의 다른 글
[React.js] Clerk (0) | 2024.10.28 |
---|---|
[React.js] use-debounce 패키지 (1) | 2024.10.27 |
[React.js] antd 컴포넌트 라이브러리 (1) | 2024.10.23 |
[React.js] 일반 CSS와 CSS Module 비교 (0) | 2024.10.16 |
[React.js] URL의 파리미터(Parameter) 값 가져오기 (1) | 2024.10.02 |
[React.js] index.js로 컴포넌트(Component), 페이지(Page) 관리하기 (0) | 2024.10.01 |
[React.js] Thunk API (Redux Toolkit) (1) | 2024.09.28 |
[React.js] 리액트 라우터(React Router) (0) | 2024.09.26 |