// 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
import { legacy_createStore as createStore } from 'redux';
const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector('span');
number.innerText = 0;
const ADD = 'ADD';
const MINUS = 'MINUS';
// 리듀서는 state와 action을 인자로 받는다.(EventListener 같은 역할)
const countReducer = (count = 0, action) => {
switch (action.type) {
case ADD:
return count + 1;
case MINUS:
return count - 1;
default:
return count;
}
};
const countStore = createStore(countReducer);
const onChage = () => {
number.innerText = countStore.getState();
};
// subscribe을 통해 html을 update 해준다.
countStore.subscribe(onChage);
// dispatch를 통해 액션을 발생시킨다.(triggering an event)
// dispatch의 인자로 action을 넣는다.
// action은 항상 Object 타입이어야 한다.
const handleAdd = () => {
countStore.dispatch({ type: ADD });
};
const handleMinus = () => {
countStore.dispatch({ type: MINUS });
};
add.addEventListener('click', handleAdd);
minus.addEventListener('click', handleMinus);
reducer
를 통해서만 state를 변경시킬 수 있다.
reducer와 커뮤니케이션 하는 방법은 dispatch
에 action
을 담아 보내는 것.
store.dispatch(action)
이 때, action
은 Object 타입이다.
변경된 state를 html에 반영시키기 위해 subscribe
사용
store.subscribe(updateFunction);