노마드코더 : 리덕스

정혜지·2022년 10월 21일

1021

basic-redux(vanilla)

import { createStore } from 'redux'; 

const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector("span");

const ADD = "ADD";
const MINUS = "MINUS"

number.innerHTML = 0;

const countModifier = (count = 0, action) => {
  switch (action.type) {
    case ADD :
      return count + 1;
    case MINUS :
      return count - 1;
    default:
      return count;
  }
  return count;
}
// modifier와 reducer가 return하는 건 application의 data가 된다.
// countModifier = initialState 
// data를 수정하는 유일한 방법 : reducer

const countStore = createStore(countModifier);

const onChange = () => {
  number.innerHTML = countStore.getState();
}

countStore.subscribe(onChange)

add.addEventListener('click', () => countStore.dispatch({type: ADD}))
minus.addEventListener('click', () => countStore.dispatch({type: MINUS}))

복습

import { createStore } from 'redux'; 

const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector("span");

number.innerHTML = 0;

// state
const ADD = "ADD";
const MINUS = "MINUS";

//reducer, reducer(state, action)
const countModify = (count = 0,  action) => {
  switch (action.type) {
    case ADD:
      return count + 1;
    case MINUS:
      return count - 1;
    default:
      return count;
  }
}

//createStore(reducer)
const countStore = createStore(countModify);

const onChange = () => {
  number.innerHTML = countStore.getState();
}

add.addEventListener('click', () => countStore.dispatch({type: ADD}))
minus.addEventListener('click', () => countStore.dispatch({type: MINUS}))

console.log(countStore.getState());

countStore.subscribe(onChange);
profile
오히려 좋아

0개의 댓글