바닐라 자바스크립트에서 리덕스 사용하기

런던행·2020년 7월 13일
0

React

목록 보기
1/6

프로젝트 생성

yarn global add parcel-bundler
mkdir vanilla-redux
cd vanilla-redux
yarn init -y
yarn add reux

parcel-bundler 통해서 아주 쉽고 빠르게 웹 어플리케이션 프로젝트 구성 가능

index.html

<html>
    <head>
        <link ref="stylesheet" type="text/css" href="index.css" />
    </head>
    <body>
        <div>바닐라 자바스크립트</div>


        <div class="toggle"></div>
        <hr />
        <h1>0</h1>

        <button id="increase"> +1 </button>
        <button id="decrease"> -1 </button>

        <script src="./index.js"></script>
    </body>
</html>

index.css

.toggle {
    border: 2px, solid black;
    width: 64px;
    height: 64px;
    border-radius: 32px;
    box-sizing: border-box
}

.toggle.active {
    background: yellow;
}

index.js

console.log('hello')


const divToggle = document.querySelector('.toggle')
const counter = document.querySelector('h1')
const btnIncrease = document.querySelector('#increase')
const btnDecrease = document.querySelector('#decrease')

// 액션 타입 (1)
const TOGGLE_SWITCH = 'TOGGLE_SWITCH'
const INCREASE = 'INCREASE'
const DECREASE = 'DECREASE'

// 액션 생성 함수 (2)
const toggleSwitch = () => ({ type: TOGGLE_SWITCH })
const increase = difference => ({ type: INCREASE, difference })
const decrease = () => ({ type: DECREASE })

// 초기 상태 값 (3)
const initialState = {
    toggle: false,
    counter: 0
}

// 리듀서 정의 (4)
function reducer(state = initialState, action) {
    switch(action.type) {
        case TOGGLE_SWITCH:
            return {
                ...state,
                toggle: !state.toggle
            }
        case INCREASE:
            return {
                ...state,
                counter: state.counter + action.difference 
            }
        case DECREASE:
            return {
                ...state,
                counter: state.counter - 1
            }
        default:
            return state

    }
}

// 스토어 생성 (5)
import { createStore } from 'redux'

const store = createStore(reducer)

const render = () => {
    const state = store.getState()  // 현재 상태를 불러온다.

    if (state.toggle) {
        divToggle.classList.add('active')
    } else {
        divToggle.classList.remove('active')
    }

    counter.innerHTML = state.counter
}


render()
// 구독하기 (6)
store.subscribe(render)  // 상태가 바뀔 때마다 render 함수 호출

divToggle.onclick = () => {
    store.dispatch(toggleSwitch())
}

btnIncrease.onclick = () => {
    store.dispatch(increase(1))
}

btnDecrease.onclick = () => {
    store.dispatch(decrease())
}

프로젝트 실행

 parcel index.html
profile
unit test, tdd, bdd, laravel, django, android native, vuejs, react, embedded linux, typescript

0개의 댓글