티스토리 뷰

 

 

reducer의 state  값이 변화될 때마다 감지하는 subscribe 함수에 대해 알아보겠습니다.

 

우리는 어떠한 이벤트가 발생되었을때 data의 값이 변화가 되어야 할 때가 있는데,

 

 redux 에서  createStore로 생성한  data 가 담겨있는 곳에 변화가 있을 시 

 

적절한 다음 명령을 실행하게  할수있게 하는 subscribe 함수가 있다.

 

import { createStore } from "redux";

const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.getElementById("number");

const reducer = (count = 0, action) => {
  if (action.type === "ADD") {
    return count + 2;
  } else if (action.type === "MINUS") {
    return count - 1;
  } else {
    return count;
  }
};

const countStore = createStore(reducer);
 
const onChange = () => {
  number.innerText = countStore.getState();  
};
countStore.subscribe(onChange);  
  
add.addEventListener("click", () => countStore.dispatch({ type: "ADD" }));
minus.addEventListener("click", () => countStore.dispatch({ type: "MINUS" }));
 

코드를 해석해보면 

Id가 add 인 태그를 클릭하였을때 ,  reducer 에  dispatch 로  action을 보내 action의 type 에 따라
명령이실행되어 state가 변화됩니다 , state가 변화가 되면  subscirbe( ) 함수가  state의 변화를 감지해서
onChange () 함수 를 실행시키고 add태그의 innerText 값을 countStore.getState() 명령을 통해
현재 state 값 을 넣어줍니다. 
 
이상 subscribe() 함수 의 역할과 사용방법이었습니다. 
 
* 잘못된 부분이 있다면 댓글 부탁드립니다 *
 

 

'Redux' 카테고리의 다른 글

React-Redux 삭제 방법 2 (추가글)  (0) 2022.02.28
React-Redux 사용방법  (0) 2022.02.26
React-Redux 삭제 방법 1  (0) 2022.02.26
Redux state 에 올바른 데이터 추가방법!  (0) 2022.02.26
Redux 사용법 !  (0) 2022.02.25