클라이언트/JavaScript
[자바스크립트(JavaScript)] 리덕스(Redux)
Hana_h
2024. 2. 13. 09:23
// 리덕스, Redux
- Cross-Component나 App-Wide 상태 관리 라이브러리
// Cross-Component State
- 여러 컴포넌트에 영향을 미치는 state
~ 모달창 open / close
// App-Wide State
- 애플리케이션 전체에 영향을 미치는 state
~ 사용자 인증
- 하나의 중앙 데이터 저장소
> 딱 하나에 원하는 state를 모두 저장한다.
- 컴포넌트는 저장소에 있는 state를 직접 변경하지 않고 Reducer 함수를 이용하여 변경한다.
> Component ->(dispatch) action -> Reducer 함수 -> Central State Store
1. 저장소 생성
const redux = require('redux');
const 저장소명 = redux.createStore();
2. Reducer 함수 추가
const reducer함수명 = (state = 기본값, action) => {
return {
};
}
- 2개의 parameter(기존 상태, action )를 받는다.
- 새로운 상태 객체를 return 한다. (이론적으로는 다른 형태로도 가능하지만, 실제로는 객체 return)
3. 저장소에 reducer 함수 전달
const redux = require('redux');
const 저장소명 = redux.createStore(reducer함수명);
4. 저장소를 subscribe 하는 함수 정의
const subscriber함수명 = () => {
const 최신상태명 = 저장소명.getState();
};
4. 저장소를 subscribe 하는 함수 실행
저장소명.subscribe(subscribe 함수명);
5. action 발송(dispatch)
저장소명.dispatch(action 객체);
const reducer함수명 = (state = 기본값, action) => {
if(action.type === '정의된type') {
return ...
}
return state;
}
- action 객체에 type을 선언하여 reducer 함수에서 구분할 수 있게 한다.