π₯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);
π μλͺ»λ κ°λ μ λ¬μ΄ μλ€λ©΄ λκΈ λΆνλ립λλ€. μ μ μ±μ₯μ ν° λμμ΄ λ©λλ€π€
λ°μν