본 글은 노마더코더의 초보자를 위한 리덕스 101 강의를 들으며 작성한 글입니다.
Redux의 Store를 출력해보면 다음과 같은 함수들이 나온다.
getState()는 store 내부의 현재 state값을 반환해주는 함수이고
dispatch()는 action에게 메세지를 보내기 위해 사용하는 함수라는 것을 우리는 배웠다.
그러면 subscribe() 함수는 어떤 함수일까?
subscribe
import { createStore } from "redux";
const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");
const ADD = "ADD";
const MINUS = "MINUS";
const countModifier = (count = 0, action) => {
switch (action.type) {
case ADD:
return count + 1;
case MINUS:
return count - 1;
default:
return count;
}
};
const onChange = () => {
number.innerText = countStore.getState();
};
const countStore = createStore(countModifier);
countStore.subscribe(onChange);
add.addEventListener("click", () => countStore.dispatch({ type: ADD }));
minus.addEventListener("click", () => countStore.dispatch({ type: MINUS }));
subscribe는 store 안에 있는 변수가 바뀔 때 알 수 있게 해주는 함수이다.
일종의 onChange 함수와 비슷하다고 볼 수 있다.
countStore.subscribe(function)을 실행하면 store내의 state가 변경되었을 때, function 함수를 실행시킨다.
위 코드에서 add버튼을 클릭해서 countModifier에 ADD 함수부를 실행하면 store 내부 state인 count의 값이 바뀌게 되고
값이 바뀌면 onChange 함수가 실행되어 number 내부에 innerText를 업데이트 된 count 값으로 업데이트해준다.
'Frontend > 상태관리' 카테고리의 다른 글
[React-Redux] mapDispatchProps (0) | 2022.01.14 |
---|---|
[React-Redux] connect, mapStateProps (0) | 2022.01.13 |
[Redux] NEVER MUTATE STATE (0) | 2022.01.13 |
[Redux] Actions - Dispatch (0) | 2022.01.13 |
[Redux] Store, Reducer (0) | 2022.01.12 |