Redux
[Redux] Redux기초 프로그래밍
류정식
2021. 2. 21. 16:48
0. 구현 사항
위의 사진처럼 버튼을 누르면 숫자가 올라가거나, 내려가는 프로그램을 구현할 것이다.
1. None Redux, Only Vanilla JS
const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.getElementById("span");
let count = 0;
number.innerText = count;
const updateText = () => {
number.innerText = count;
};
const handleAdd = () => {
count = count + 1;
updateText();
};
const handleMinus = () => {
count = count - 1;
updateText();
};
add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);
이렇게 js로 구현 가능하다.
2. With Vanilla Redux
import { createStore } from "redux";
const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.getElementById("span");
number.innerText=0;
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 countStore = createStore(countModifier);
const onChange=()=>{
number.innerText=countStore.getState();
};
countStore.subscribe(onChange);
const handleAdd=()=>{
countStore.dispatch({type : ADD})
}
const handleMinus=()=>{
countStore.dispatch({type : MINUS})
}
add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);
(1). store 생성
const countStore = createStore(countModifier);
-createStore를 통해서 생성가능하다.
(2). reducer 생성
const countModifier = (count = 0, action) => {
switch(action.type){
case ADD:
return count +1;
case MINUS:
return count -1;
default:
return count;
}
}
-reducer : data를 modify하는 함수다.
switch를 통해서 각각의 action에 따른 return하는 state를 값을 정할 수 있다.
(3). dispatch
const handleAdd=()=>{
countStore.dispatch({type : ADD})
}
const handleMinus=()=>{
countStore.dispatch({type : MINUS})
}
-dispatch를 통해서 변화하는 state값을 변화시킬 수 있다.
(4). subscribe
const onChange=()=>{
number.innerText=countStore.getState();
};
countStore.subscribe(onChange);
-subscribe : 우리에게 store안의 변화를 알 수 있게해준다.