Redux

Fstone·2020년 12월 2일
0
post-thumbnail

Redux

  • Web, App 상태관리 library
  • React와 별개의 javascript library이다.

Store

  • App은 하나의 Redux store를 가질 수 있다.
  • Store는 Reducer를 통해 Data, 상태를 전달 받는다.
  • Store는 Dispatch를 통해 상태 변화를 Reducer에 전달한다. 이 때 전달하는 상태 변화를 action이라 하고 action은 plain obejct여아 한다.

Learn Redux

Install:

npm install redux

Create Store & Reducer

import {createStore} from "redux"

const reducer = (state, action) => {
  // do something with state as a delivered action 
}

const reduxStore = createStore(reducer);
  • reducer는 항상 상태와 상태 관리를 위한 action을 알고 있어야하며 store를 생성하기 위해 callback 인자로 전달하여야 한다.

  • Redux store는 4가지 Property methods를 가지고 있다.

    • dispatch : reducer로 action을 전달한다.

    • getState : store가 가지고 있는 상태 값을 불러온다.

    • replaceReducer : 최근까지 사용된 Reducer를 바꾼다.

    • subscribe : dispatch가 실행되어 data 또는 상태의 변화가 생길 경우 실행된다.

Dispatch

import {createStore} from "redux"

const reducer = (state, action) => {
  // do something with state as a delivered action 
}

const reduxStore = createStore(reducer);

reduxStore.dispatch({ type: "action"})
  • dispatch가 전달받은 객체는 reducer에 인자로 받는 action을 가리킨다. action.type으로 접근할 수 있다.

  • store에서 dispatch를 통해 reduceraction이란 message를 전달하는 것이다.

Subscribe

import {createStore} from "redux"

const reducer = (state, action) => {
  // do something with state as a delivered action 
}

const reduxStore = createStore(reducer);

const handleState = () => {
  // do something to handle state
}

reduxStore.subscribe(handleState);

reduxStore.dispatch({ type: "action"})
  • dispatch를 통해 reducer에서 data 또는 상태 값의 변화가 생기면 subscribe에 전달 된 함수를 호출한다.

Counter with Javascript, Redux

import { 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";

const countModifier = (count = 0, action) => {
  switch (action.type) {
    case "ADD":
      return (count += 1);

    case "MINUS":
      return (count -= 1);

    default:
      return count;
  }
};

const countStore = createStore(countModifier);

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

countStore.subscribe(onChange);

add.addEventListener("click", () => countStore.dispatch({ type: ADD }));

minus.addEventListener("click", () => countStore.dispatch({ type: MINUS }));

Simple toDo List with JS, redux

import { createStore } from "redux";

const form = document.querySelector("form");
const input = document.querySelector("input");
const ul = document.querySelector("ul");

const ADD_TODO = "ADD_TODO";
const DELETE_TODO = "DELETE_TODO";

const addToDo = (text) => {
  return {
    type: ADD_TODO,
    text,
  };
};

const deleteTodo = (id) => {
  return {
    type: DELETE_TODO,
    id,
  };
};

const reducer = (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return [{ text: action.text, id: Date.now() }, ...state];
    case DELETE_TODO:
      return state.filter((todo) => todo.id !== action.id);
    default:
      return state;
  }
};

const store = createStore(reducer);

store.subscribe(() => console.log(store.getState()));

const dispatchAddToDo = (text) => {
  store.dispatch(addToDo(text));
};

const dispatchDeleteTodo = (e) => {
  const id = parseInt(e.target.parentNode.id);
  store.dispatch(deleteTodo(id));
};

const paintTodos = () => {
  const toDos = store.getState();
  ul.innerHTML = "";
  toDos.forEach((todo) => {
    const li = document.createElement("li");
    const btn = document.createElement("button");
    btn.innerText = "DEL";
    btn.addEventListener("click", dispatchDeleteTodo);
    li.id = todo.id;
    li.innerText = todo.text;
    li.appendChild(btn);
    ul.appendChild(li);
  });
};

store.subscribe(paintTodos);

const onSubmit = (e) => {
  e.preventDefault();
  const toDo = input.value;
  input.value = "";
  dispatchAddToDo(toDo);
};

form.addEventListener("submit", onSubmit);

Reference

https://redux.js.org/

0개의 댓글