참치코더의 꿈 메모장

Javascript / 리덕스(Redux) - 개념 미니 정리 본문

Javascript

Javascript / 리덕스(Redux) - 개념 미니 정리

참치깡 2025. 9. 9. 03:57
728x90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");
 
number.innerText = 0;
 
const ADD = "ADD";
const MINUS = "MINUS";
 
const countModifier = (count = 0, action) => {
  if (action.type === "ADD") {
    return count + 1;
  } else if (action.type === "MINUS") {
    return count - 1;
  }
  return count;
};
 
const countStore = createStore(countModifier);
 
const onChange = () => {
    number.innerText = countStore.getState();
};
 
countStore.subscribe(onChange);
 
add.addEventListener("click", () => countStore.dispatch({type : ADD}));
minus.addEventListener("click", () => countStore.dispatch({type : MINUS}));
 
cs

 

1. store 생성 (내가 관리하는 모든 state (data)를  관리하기 위한 데이터 저장소 생성) , 함수로 연결 설정

  const countStore = createStore(countModifier);

 

2. 초기값 생성 및 dispatch로 스토어 내에 있는 action 호출 및 전달

add.addEventListener("click", () => countStore.dispatch({type : ADD}));
minus.addEventListener("click", () => countStore.dispatch({type : MINUS}));

 

3. 연결 되었는 함수에서 초기값 설정 및 해당 dispatch 전달 값 action 처리

 

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

 

4.  Store에 있는 값 구독 및 조회하기

 

const onChange = () => {
    number.innerText = countStore.getState();
};

 

countStore.subscribe(onChange);

 

728x90
Comments