요르딩딩
섹션10. userReducer 본문
728x90
반응형
9.1) useReducer를 소개합니다





9.2) 투두리스트 업그레이드
import "./App.css";
import { useRef, useState } from "react";
import Header from "./components/Header";
import Editor from "./components/Editor";
import List from "./components/List";
const mockData = [
{
id: 0,
isDone: false,
content: "React 공부하기",
date: new Date().getTime(),
},
{
id: 1,
isDone: false,
content: "빨래하기",
date: new Date().getTime(),
},
{
id: 2,
isDone: false,
content: "노래 연습하기",
date: new Date().getTime(),
},
];
// useState -> useReducer 사용하기 !!!
function reducer(state, action) {
switch (action.type) {
case "CREATE":
return [action.data, ...state]; // 앞에 생성!!!
case "UPDATE":
return state.map((item) => // map돌면서 해당값만 수정!!!
item.id === action.targetId
? {...item, isDone: !item.isDone}
: item
);
case "DELETE":
return state.filter((item => item.id !== action.targetId)) // filter하기!!!
);
default:
return state;
}
}
function App() {
// todos가 복잡한 객체인 경우는 useReducer많이 사용. 간단한 값은 useState사용!!!
const [todos, dispatch] = useReducer(reducer, mockData); // 초기값도 세팅
const idRef = useRef(3);
// useReducer방식 추가
const onCreate = (content) => {
dispatch({
type : "CREATE",
data : {
id : idRef.current++,
isDonw: false,
content: content,
date : new Date().getTime(),
},
});
};
const onUpdate = (targetId) => {
dispatch({
type : "UPDATE",
targetId : targetId
});
};
const onDelete = (targetId) => {
dispatch({
type : "DELETE",
targetId : targetId
});
};
return (
<div className="App">
<Header />
<Editor onCreate={onCreate} />
<List
todos={todos}
onUpdate={onUpdate}
onDelete={onDelete}
/>
</div>
);
}
export default App;
728x90
반응형
'[강의] > [한 입 크기로 잘라 먹는 리액트(React.js)]' 카테고리의 다른 글
섹션13. 프로젝트3. 감정 일기장 (0) | 2025.04.14 |
---|---|
섹션11. 최적화 (0) | 2025.04.07 |
섹션9. 프로젝트2. TODO 리스트 (0) | 2025.04.02 |
섹션8. 라이프사이 (0) | 2025.04.02 |
섹션7. 프로젝트1. 카운터 (0) | 2025.04.02 |