combineReducer - ToDo 기능 추가
현재까지 만든 카운트 앱에서 ToDo앱을 추가해보겠습니다.
Reducer는 하나만 존재하지만 안에 여러개 sub reducer를 생성한 후 root reducer에 combineReducers하면 됩니다.
interface Action {
  type: string
}
const counter = (state = 0, action: Action) => {
  switch(action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
}
export default counter;
기존에 reducer폴더안에 있는 index.tsx의 코드입니다. 이 코드를 그대로 복붙해서 counter.tsx파일에 옮깁니다.
enum ActionType {
  ADD_TODO = 'ADD_TODO',
  DELETE_TODO = 'DELETE_TODO'
}
interface Action {
  type: ActionType;
  text: string;
}
const counter = (state = [], action: Action) => {
  switch(action.type) {
    case "ADD_TODO":
      return [...state, action.text];
    default:
      return state;
  }
}
export default counter;
reducer폴더안에 있는 todos.tsx의 코드입니다.
import {combineReducers} from 'redux';
import counter from './counter';
import todos from './todos';
const rootReducer = combineReducers({
  counter,
  todos
})
export default rootReducer;
reducer폴더안에 있는 index.tsx의 현재 코드입니다.
combineReducers를 사용해서 counter과 todos를 결합했습니다.
createStore에 rootReducer로 대체

루트경로에 있는 index.tsx파일에 기존에 counter를 rootReducer로 대체합니다.

루트경로에 있는 index.tsx파일에 store.dispatch를 다시 작성해서 console.log에 찍어서 제대로 나오는지 확인하려고 합니다.
여기서 에러가 많이 날 겁니다.
- App.tsx파일에 Props 타입 중 value를 임위적으로 any로 변경
 - App.tsx파일에 Clicked: {value} times를 임위적으로 주석처리함
 
위에 대로 처리하면 에러 사항이 없을 겁니다.
Provider를 렌더링
npm install react-redux --save
위 명령어를 통해 react전용 redux를 설치합니다.

루트경로에 있는 index.tsx파일에 App를 Provider로 감싸줍니다.
Provider에서 store를 명시해줘야 에러 안 생깁니다.
ToDo UI 생성

src폴더 안에 App.tsx파일 추가 코드입니다.
useSelector
useSelector hooks를 이용해서 store의 값을 가져올 수 있습니다.
const result: any = useSelector(selector:Function, equalityFn?: Function)

App.tsx파일의 추가 부분입니다.
export type RootState = ReturnType<typeof rootReducer>;
reducer폴더안에 index.tsx파일에 위와 같이 RootState 타입을 밖으로 보내야 App.tsx파일에 타입에러 안 뜹니다.
useDispatch
store에 있는 dispatch 함수에 접근하는 hooks입니다.

루트경로에 있는 index.tsx파일 중 store.dispatch부분을 삭제합니다.

App.tsx중 useDispatch를 정의하고 addTodo함수에 사용합니다.
'배워서 따라하는 포플 > react-redux를 이용한 앱' 카테고리의 다른 글
| Redux앱(3) - middleware (0) | 2023.09.23 | 
|---|---|
| Redux앱(1) - 카운트 앱 생성 (0) | 2023.09.23 |