Pure Redux : 01
Redux
Javascript application들의 state(상태)를 관리하는 방법이다.
javascript의 application들이지 react의 application이 아니다!
redux는 react와 별개이다.
redux는 angular, vue.js, (프레임워크 없는)vanilla.js 에서도 쓸 수 있다.
redux는 react에 의존하는 라이브러리가 아니다.
counter 예시로 알아보는 Vanilla - redux
Vanilla.js
vanilla javascript로 counter 만들기
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>Vanilla Redux</title>
</head>
<body>
<button id="add">Add</button>
<span></span>
<button id="minus">Minus</button>
</body>
</html>
index.js
const plus = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");
let count = 0;
number.innerHTML=count;
// count를 더하고(handleAdd) 빼기만(handleMinus) 할 뿐, 값을 업데이트 하지 않음. number.innerHTML=count;는 한번만 일어나기 때문.
// ㄴ> updateText 있는 이유.
// html에 뭔가가 바뀌었다고 알려주기 위해 함수를 쓴다는 것 자체가 리덕스가 멋진것 중 하나이다.
const updateText =()=>{
number.innerHTML=count;
}
const handleAdd=()=>{
count+=1;
updateText();
}
const handleMinus=()=>{
count-=1;
updateText();
}
plus.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

이 application에서 data가 바뀌는 곳은! 유일하게 let count = 0; 이다.
-> count를 increse시키거나 decrese시키는 유일한 data
Vanilla Redux 🌝
위에서 vanilla javascript로 만든 counter 예시를 Redux로 만들어보자.
redux 파헤치기 ⚓
📍 Redux를 사용
터미널에 yarn add redux 해준다.
( npm사용시에는 npm install redux 하기! )

📍 redux에서 createStore import하기
import { createStore } from "redux";
redux에는 createStore라는 함수가 있다.
Store은 data / state 를 저장하는 곳.
( state는 application에서 바뀌는 data )
Store가 하는 일 : 기본적으로 data를 넣을 수 있는 장소를 생성한다.
-> redux는 data를 관리하는데 도와주는 역할을 하기 위해 만들어 진 것!
-> 현재 couter 예시에서 redux가 -1 or +1을 count하는 것을 도와주기 위해 만들어진 것!
-> data를 어딘가에 넣어줘야 하고, 그 data는 store이라는 곳에 저장(go on)되어야 한다.
📍 store 만들기
const store = createStore();
-> createStore에 마우스를 대보면, 아래와 같은 텍스트가 뜬다.
(alias) createStore<any, Action<any>, any, any>(reducer: Reducer<any, Action<any>>, enhancer?: StoreEnhancer<any, any>): any (+1 overload)
import createStore
-> createStore라는 함수는 reducer를 받기를 요구.
const reducer = () => {};
const store = createStore(reducer);
->reducer라는 함수를 만들어서 createStore에 넣어준다.
-> reducer는 data를 modify(수정)하는 것을 책임지는 함수로, reducer가 return하는 것은 application에 있는 data가 된다.
( ex) count를 increase or decrease )
📍 reducer or modifier는 ~!
1) data를 바꿔준다.
2) return하는 것은 application에 있는 data이다.
const countModifier = ()=>{
return "hello";
};
const countStore = createStore(countModifier);
console.log(countStore);
console.log(countStore.getState());
-> hello를 get하게 된다.
const countModifier = (state)=>{
console.log(state)
return state;
};
const countStore = createStore(countModifier);
-> countModifier를 initial state로 불러 온다.
-> state가 undefined 되었다.
const countModifier = (state = 0)=>{
console.log(state)
return state;
};
const countStore = createStore(countModifier);
-> defualt 더할 경우, state가 없다면, defualt로 state는 0이 된다.
-> state를 initializing하는 것.
const countModifier = (state = 0)=>{
return state;
};
const countStore = createStore(countModifier);
console.log(countStore.getState())
-> get state하면state는 0과 같게 된다.
Javascript application들의 state(상태)를 관리하는 방법이다.javascript의 application들이지 react의 application이 아니다!redux는 react와 별개이다.redux는 angular, vue.js, (프레임워크 없는)vanilla.js 에서도 쓸 수 있다.redux는 react에 의존하는 라이브러리가 아니다.Vanilla - reduxVanilla.jsvanilla javascript로 counter 만들기index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>Vanilla Redux</title>
</head>
<body>
<button id="add">Add</button>
<span></span>
<button id="minus">Minus</button>
</body>
</html>
index.js
const plus = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");
let count = 0;
number.innerHTML=count;
// count를 더하고(handleAdd) 빼기만(handleMinus) 할 뿐, 값을 업데이트 하지 않음. number.innerHTML=count;는 한번만 일어나기 때문.
// ㄴ> updateText 있는 이유.
// html에 뭔가가 바뀌었다고 알려주기 위해 함수를 쓴다는 것 자체가 리덕스가 멋진것 중 하나이다.
const updateText =()=>{
number.innerHTML=count;
}
const handleAdd=()=>{
count+=1;
updateText();
}
const handleMinus=()=>{
count-=1;
updateText();
}
plus.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

이 application에서 data가 바뀌는 곳은! 유일하게 let count = 0; 이다.
-> count를 increse시키거나 decrese시키는 유일한 data
Vanilla Redux 🌝vanilla javascript로 만든 counter 예시를 Redux로 만들어보자.redux 파헤치기 ⚓ 📍 Redux를 사용
터미널에 yarn add redux 해준다.
( npm사용시에는 npm install redux 하기! )

📍 redux에서 createStore import하기
import { createStore } from "redux";
redux에는createStore라는 함수가 있다.Store은data/state를 저장하는 곳.
(state는 application에서 바뀌는data)Store가 하는 일 : 기본적으로data를 넣을 수 있는 장소를 생성한다.
->redux는data를 관리하는데 도와주는 역할을 하기 위해 만들어 진 것!
-> 현재 couter 예시에서redux가 -1 or +1을 count하는 것을 도와주기 위해 만들어진 것!
->data를 어딘가에 넣어줘야 하고, 그data는store이라는 곳에 저장(go on)되어야 한다.
📍 store 만들기
const store = createStore();
-> createStore에 마우스를 대보면, 아래와 같은 텍스트가 뜬다.
(alias) createStore<any, Action<any>, any, any>(reducer: Reducer<any, Action<any>>, enhancer?: StoreEnhancer<any, any>): any (+1 overload)
import createStore
-> createStore라는 함수는 reducer를 받기를 요구.
const reducer = () => {};
const store = createStore(reducer);
->reducer라는 함수를 만들어서 createStore에 넣어준다.
-> reducer는 data를 modify(수정)하는 것을 책임지는 함수로, reducer가 return하는 것은 application에 있는 data가 된다.
( ex) count를 increase or decrease )
📍 reducer or modifier는 ~!
1) data를 바꿔준다.
2) return하는 것은 application에 있는 data이다.
const countModifier = ()=>{
return "hello";
};
const countStore = createStore(countModifier);
console.log(countStore);
console.log(countStore.getState());
-> hello를 get하게 된다.
const countModifier = (state)=>{
console.log(state)
return state;
};
const countStore = createStore(countModifier);
-> countModifier를 initial state로 불러 온다.
-> state가 undefined 되었다.
const countModifier = (state = 0)=>{
console.log(state)
return state;
};
const countStore = createStore(countModifier);
-> defualt 더할 경우, state가 없다면, defualt로 state는 0이 된다.
-> state를 initializing하는 것.
const countModifier = (state = 0)=>{
return state;
};
const countStore = createStore(countModifier);
console.log(countStore.getState())
-> get state하면state는 0과 같게 된다.
유일하게 countModifier만 data / state를 modify할 수 있다!
밖에 있는 다른 함수는 ❌❌❌
-> redux의 멋진 기능!
-> redux는 data가 기본적으로 한 곳에만 있다
countModifier로 ++ or -- 를 어떻게 할까? -> action을 통해서 가능하다!
count modify하기 ~ ! 🤠
action 먼저 알고가자!
redux에서function을 부를때 쓰는 두번째parameterorargument이다.reducer과 소통하기 위한 방법.reducer에게action을 보내는 방법 ↓↓store.dispatch({key:value});
📍
state,action출력const countModifier = (count = 0, action)=>{ console.log(count, action); }; const countStore = createStore(countModifier);
-> 현재의 상태인
state가 있고, 만약에 이 존재하지 않는다면 0을 출력.
->action은 현재 다소 난해한 것이 출력된다.
일단, countModifier이 count+1 or count-1을 return하기 위해 action의 도움을 받아야 한다.
📍
countModifier가 2번 불렸다const countModifier = (count = 0, action) => { console.log(action); return count; }; const countStore = createStore(countModifier); countStore.dispatch({type:"Hi~"});
-> 첫번째는 initialized된
function( initialize with action ),
두번째는type이라는 다른action.
📍
dispatch로countModifier로 메세지 보내기const countModifier = (count = 0, action) => { if(action.type ==="Add"){ console.log("they are telling me to add one 🤟 ") } return count; }; const countStore = createStore(countModifier); countStore.dispatch({type:"Add"});
-> 전송한 메세지는
action에 넣고,action체크하기
📍 counter 기능 구현
const countModifier = (count = 0, action) => { if(action.type ==="Add"){ return count + 1; }else if(action.type ==="Minus"){ return count - 1; }else{ return count; } }; const countStore = createStore(countModifier); countStore.dispatch({type:"Add"}); // 1 countStore.dispatch({type:"Add"}); // 2 countStore.dispatch({type:"Add"}); // 3 countStore.dispatch({type:"Add"}); // 4 countStore.dispatch({type:"Add"}); // 5 countStore.dispatch({type:"Add"}); // 6 countStore.dispatch({type:"Add"}); // 7 countStore.dispatch({type:"Minus"}); // 6 console.log(countStore.getState());
count가 증가되는 이유
->count을return하면,count는 0이다.
-> 그리고countStore.dispatch()를 말하면if문 조건에 맞을 대count+1을return해준다. 즉count는 1
->return된 것은 현재의state가 된다.
-> 다시dispatch를 부른다.
📍
state상태 보기const countModifier = (count = 0, action) => { console.log(count, action) if(action.type ==="Add"){ return count + 1; }else if(action.type ==="Minus"){ return count - 1; }else{ return count; } }; const countStore = createStore(countModifier); countStore.dispatch({type:"Add"}); countStore.dispatch({type:"Add"}); countStore.dispatch({type:"Add"}); countStore.dispatch({type:"Add"}); countStore.dispatch({type:"Add"}); countStore.dispatch({type:"Add"}); countStore.dispatch({type:"Add"}); countStore.dispatch({type:"Minus"}); console.log(countStore.getState());
->
state변화를 볼 수 있다.
정리 💨
-
data를modify할 수 있는function은countModifier이다. -
밖에서
countModifier와 커뮤니케이션 할 수 있어야 하고, 그 방법은
countModifier에게action을 보내는 것이다.이제
dispatch와 모든 것들을button에 연결하고 마무리하자!!
Subscriptions 🌝
: store안의 변화를 감지한다.
📍
button에 이벤트 연결해주기import { createStore } from "redux"; const plus = document.getElementById("add"); const minus = document.getElementById("minus"); const number = document.querySelector("span"); const countModifier = (count = 0, action) => { console.log(count, action) if(action.type ==="Add"){ return count + 1; }else if(action.type ==="Minus"){ return count - 1; }else{ return count; } }; const countStore = createStore(countModifier); plus.addEventListener("click", ()=> countStore.dispatch({type:"Add"})); // 익명함수 사용해야 한다. or 함수 빼서 선언해주기. minus.addEventListener("click", ()=> countStore.dispatch({type:"Minus"}));
-> 버튼을 클릭하면 이벤트가 잘 실행된다.
-> But, 현재html은 notified되지 않았다.
countStore를 콘솔에서 다시 보면,console.log(countStore);
-> 사용하고 있는
dispatch,getState가 보이고Subscriptions가 보인다! (replaceReducer은 무시하기!)
->Subscriptions는store안에 있는 변화들을 알 수 있게 해준다.
📍
store을subscribe하기const onChange = () =>{ console.log("there was change on the store"); } countStore.subscribe(onChange);
-> 버튼을 클릭하면
store에 변화가 생긴다.
📍 UI로 보여주기~!
import { createStore } from "redux"; const plus = document.getElementById("add"); const minus = document.getElementById("minus"); const number = document.querySelector("span"); number.innerHTML= 0; const countModifier = (count = 0, action) => { if(action.type ==="Add"){ return count + 1; }else if(action.type ==="Minus"){ return count - 1; }else{ return count; } }; const countStore = createStore(countModifier); // onChange함수는 store에 변화가 있을때마다 감지해서 불려진다. const onChange = () =>{ number.innerHTML =countStore.getState(); } countStore.subscribe(onChange); plus.addEventListener("click", ()=> countStore.dispatch({type:"Add"})); // 익명함수 사용해야 한다. or 함수 빼서 선언해주기. minus.addEventListener("click", ()=> countStore.dispatch({type:"Minus"}));
data를 수정하는 유일한 곳은 reducer안 ( = countModifier )이다 ! 😝👍
학습 : 초보자를 위한 리덕스 101
Author And Source
이 문제에 관하여(Pure Redux : 01), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@gyomni/Pure-Redux-01저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
-> 현재의 상태인
-> 첫번째는 initialized된
-> 전송한 메세지는 
->
-> 버튼을 클릭하면 이벤트가 잘 실행된다.
-> 사용하고 있는
-> 버튼을 클릭하면 