๋ฐ์ํ
โญ๏ธ๋ฆฌ๋์ค๋ ๊ผญ 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);
๐ ์๋ชป๋ ๊ฐ๋ ์ ๋ฌ์ด ์๋ค๋ฉด ๋๊ธ ๋ถํ๋๋ฆฝ๋๋ค. ์ ์ ์ฑ์ฅ์ ํฐ ๋์์ด ๋ฉ๋๋ค๐ค
๋ฐ์ํ
'๐ฅFrontEnd > Redux' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ ์ญ ์ํ์ ์ง์ญ ์ํ ๊ตฌ๋ถ์ ํด๋ณด์ (0) | 2022.10.11 |
---|---|
Redux Toolkit ์ฌ์ฉ๋ฐฉ๋ฒ (0) | 2022.07.28 |
๋ฆฌ๋์ค์์ ๊ฐ์ฅ ์ค์ํ ์ , ๊ธฐ์กด์ state๋ฅผ ๋ณ๊ฒฝํด์๋ ์๋๋ ์ด์ ! (0) | 2022.07.11 |
์ฝ๋๋ก ๋ณด๋ ๋ฆฌ๋์ค ๊ธฐ์ด (0) | 2022.07.10 |
TIL) REDUX, redux ๊ธฐ์ด, ๋ฆฌ๋์ค ๊ตฌ์กฐ, Redux์ ์ธ ๊ฐ์ง ์์น (0) | 2022.07.06 |