Redux-Typescript

notion image
보일러플레이트
npx create-react-app react-redux-ts —template typescript yarn add redux react-redux redux-thunk @types/react-redux
 
state폴더안에 reducers 폴더를 만들고 bankReducer.ts파일을 만든다.
notion image
→ reducer함수, action별로 case를 나눈다. 이때 파라미터의 state와 action의 타입을 정해주어야한다.
notion image
→state는 숫자 타입으로 나와야하고 초기값은 0이기때문에, initialState=0; 을 할당한다.
→action타입을 정하는데, action 마다 다르게 나눠주어야하는데, interface를 이용해서 해당 action 마다 타입을 따로 정해준다.
→ interface로 나누어놨던 action type을 type union형태로 정해준다.
notion image
→action폴더에서 해당 action interface type을 관리한다.
notion image
→ type의 value가 string이므로 사람이라면 실수 할 수 있다. 따라서 enum형태로 action-type폴더를 만들어 따로 관리한다.
notion image
→ 우리가 정한 타입만 뜨기때문에, 실수 할 일이 적어진다.→
notion image
→ reducers를 관리하는 index.ts에 bankReducer를 넣어준다.
→ 추가된 것, State의 리턴 타입을 정확히 정해준다.
notion image
→ action-creators를 정의한다. 기존에 지정한 action-types과 action을 불러와서 action-creators의 타입을 정해준다. Dispatch의 리턴값에 대한 type또한 정해준다.
notion image
notion image
→ 미들웨어 thunk를 사용하여 store를 만들어준다. @types/redux-thunk를 설치해준다.
notion image
→ state폴더안의 index.ts파일에 action-creators와 store reducer를 연결 시킨다.
 
notion image
→ actionCreators와 dispatch를 하나로 묶어주는 작업을 한다. bindActionCreators를 통해 distructoring이 가능하다.
→ state의 index.ts파일에서 actionCreators와 State를 불러와서, react-redux 의 useDispatch , useSelector에 붙여준다.
→ 버튼을 누르면 actionCreator+dispatch를 통해 상태가 업데이트를 시작하고 ,
→ useSelector를 통해 정의된 amount의 state값은 상태가 바뀔때마다 콜백함수로 불러오는 상태값이 되었고.
상태관리가 성공적으로 완료되었다.