Redux
Javascript
application들의 state
(상태)를 관리하는 방법이다.javascript
의 application들이지 react
의 application이 아니다!redux
는 react
와 별개이다.redux
는 angular
, vue.js
, (프레임워크 없는)vanilla.js
에서도 쓸 수 있다.redux
는 react
에 의존하는 라이브러리가 아니다.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
ormodifier
는 ~!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
을 부를때 쓰는 두번째 parameter
or argument
이다.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