리덕스는 리액트에서 사용하려고 만들어졌지만... 실제로는 다른 UI 라이브러리, 프레림워크와 함께 사용 할 수 도 있음.
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./index.css" type="text/css" />
<title>Vanilla Redux</title>
</head>
<body>
<h1>0</h1>
<button id="increase">+1</button>
<button id="decrease">-1</button>
<script src="counter.js"></script>
</body>
</html>
Javascript
const counter = document.querySelector("h1")
const btnIncrease = document.querySelector("#increase")
const btnDecrease = document.querySelector("#decrease")
const initalState = {
counter: 0,
}
const INCREASE = "INCREASE"
const DECREASE = "DECREASE"
const increase = () => ({ type: INCREASE })
const decrease = () => ({ type: DECREASE })
const reducer = (state = initalState, action) => {
switch (action.type) {
case INCREASE:
return {
...state,
counter: state.counter + 1,
}
case DECREASE:
return {
...state,
counter: state.counter - 1,
}
default:
return state
}
}
import { createStore } from "redux"
const store = createStore(reducer)
const updateCounter = () => {
const state = store.getState()
counter.innerText = state.counter
}
store.subscribe(updateCounter)
//dispatch
btnIncrease.onclick = () => {
store.dispatch(increase(1))
}
btnDecrease.onclick = () => {
store.dispatch(decrease(0))
}
- DOM 을 만든다
const counter = document.querySelector("h1") const btnIncrease = document.querySelector("#increase") const btnDecrease = document.querySelector("#decrease")
- 초기 값 설정 및 Actions 설정
const initalState = { counter: 0, } const INCREASE = "INCREASE" const DECREASE = "DECREASE" const increase = () => ({ type: INCREASE }) const decrease = () => ({ type: DECREASE })
- REDUCER 를 만든다.
const reducer = (state = initalState, action) => { switch (action.type) { case INCREASE: return { ...state, counter: state.counter + 1, } case DECREASE: return { ...state, counter: state.counter - 1, } default: return state } }
- 스토어를 만든다
import { createStore } from "redux" const store = createStore(reducer)
- 구독(subscribe)을 만든다
const updateCounter = () => { const state = store.getState() counter.innerText = state.counter } store.subscribe(updateCounter)
- dispatch를 한다(실행시킨다)
btnIncrease.onclick = () => { store.dispatch(increase(1)) } btnDecrease.onclick = () => { store.dispatch(decrease(0)) }