πŸ–₯FrontEnd/Redux

NEVER MUTATE REDUX!!

hellohailie 2022. 8. 13. 10:37
λ°˜μ‘ν˜•

β­οΈλ¦¬λ•μŠ€λŠ” κΌ­ action을 ν†΅ν•΄μ„œ μƒνƒœλ₯Ό λ³€κ²½ν•΄μ•Όν•΄μ„œ μƒˆλ‘œμš΄ 데이터λ₯Ό λ°˜ν™˜ν•΄μ•Όν•œλ‹€!! 맀우 μ€‘μš”!!⭐️

 

(μ•„λž˜ μ˜ˆμ‹œλŠ” vanilla JSμ—μ„œ μ“°λŠ” λ¦¬λ•μŠ€ μ˜ˆμ‹œ μž…λ‹ˆλ‹€. )

βŒκ·Έλž˜μ„œ μ•„λž˜μ²˜λŸΌ λ°”λ‘œ μˆ˜μ •μ„ ν•˜λ©΄ μ•ˆλœλ‹€. ❌

const reducer = (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return state.push(action.text)
    case DELETE_TODO:
      return;
    default:
      return state;
  }
};

 

πŸŸ’μ΄λ ‡κ²Œ μˆ˜μ •ν•΄μ•Όν•œλ‹€. 🟒

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

 


전체 μ½”λ“œ

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:
      const newTodoObj = { text: action.text, id: Date.now() };
      return [newTodoObj, ...state];
    case DELETE_TODO:
      return state.filter((todo) => todo.id !== parseInt(action.id)); // string ν˜•νƒœλΌμ„œ λ„˜λ²„λ‘œ λ°”κΏ”μ•Όν•œλ‹€!!
    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 = e.target.parentNode.id;
  store.dispatch(deleteTodo(id));
};

const paintTodo = () => {
  const todo = store.getState();
  ul.textContent = ""; // 이거 μ—†μœΌλ©΄ store λ°”λ€”λ•Œλ§ˆλ‹€ λͺ¨λ“  것을 repainting ν•œλ‹€.
  //innerHTML 와 textContent λ©”μ„œλ“œ λͺ¨λ‘ ν…μŠ€νŠΈ 값을 μ½μ–΄μ˜€κ³ , μ„€μ •ν•  수 μžˆλŠ” κΈ°λŠ₯을 ν•œλ‹€. innerHTMLλŠ” λ³΄μ•ˆμ— 취약함

  todo.forEach((todo) => {
    const li = document.createElement("li");
    const btn = document.createElement("button");
    btn.innerText = "DELETE";
    btn.addEventListener("click", dispatchDeleteTodo);
    li.id = todo.id;
    li.innerText = todo.text;
    li.appendChild(btn);
    ul.appendChild(li);
  });
};

store.subscribe(paintTodo); // todo의 변화에 맞게 repainting ν•˜κ³  μžˆλ‹€.

// const createTodo = (todo) => {
//   const li = document.createElement("li");
//   li.innerText = todo;
//   ul.appendChild(li);
// };

const onSubmit = (e) => {
  e.preventDefault();
  const todo = input.value;
  input.value = "";
  //createTodo(todo);
  dispatchAddTodo(todo);
};

form.addEventListener("submit", onSubmit);

 

 

πŸ˜ƒ 잘λͺ»λœ κ°œλ… 전달이 μžˆλ‹€λ©΄ λŒ“κΈ€ λΆ€νƒλ“œλ¦½λ‹ˆλ‹€. μ €μ˜ μ„±μž₯에 큰 도움이 λ©λ‹ˆλ‹€πŸ€“

λ°˜μ‘ν˜•