[ 상태 관리 ]
일기 데이터를 관리할 state를 App 컴포넌트에 작성하기
App.js
import React, { useReducer, useRef } from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import "./App.css";
import Home from "./pages/Home";
import Diary from "./pages/Diary";
import New from "./pages/New";
import Edit from "./pages/Edit";
// COMPONENTS
import MyButton from "./components/MyButton";
import MyHeader from "./components/MyHeader";
const reducer = (state, action) => {
let newState = [];
switch (action.type) {
case "INIT": {
return action.data;
}
case "CREATE": {
const newItem = {
...action.data,
};
newState = [newItem, ...state];
break;
}
case "REMOVE": {
newState = state.filter((it) => it.id !== action.targetId);
break;
}
case "EDIT": {
newState = state.map((it) =>
it.id === action.data.id ? { ...action.data } : it
);
break;
}
}
return state;
};
export const DiaryStateContext = React.createContext();
export const DiaryDispatchContext = React.createContext();
function App() {
const [data, dispatch] = useReducer(reducer, []);
const dataId = useRef(0);
//CREATE
const onCreate = (date, content, emotion) => {
dispatch({
type: "CREATE",
data: {
id: dataId.current,
data: new Date(date).getTime(),
content,
emotion,
},
});
dataId.current += 1;
};
//REMOVE
const onRemove = (targetId) => {
dispatch({ type: "REMOVE", targetId });
};
//EDIT
const onEdit = (targetId, date, content, emotion) => {
dispatch({
type: "EDIT",
data: {
id: dataId,
data: new Date(date).getTime(),
content,
emotion,
},
});
};
return (
<DiaryStateContext.Provider value={data}>
<DiaryDispatchContext.Provider value={(onCreate, onEdit, onRemove)}>
<BrowserRouter>
<div className="App">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/new" element={<New />} />
<Route path="/diary/:id" element={<Diary />} />
<Route path="/diary" element={<Diary />} />
<Route path="/edit" element={<Edit />} />
</Routes>
</div>
</BrowserRouter>
</DiaryDispatchContext.Provider>
</DiaryStateContext.Provider>
);
}
export default App;
'Front-End > React' 카테고리의 다른 글
[ React ] React 실전 ② 프로젝트 기초 공사 1 (0) | 2022.11.02 |
---|---|
[ React ] React 실전 ① 페이지 라우팅 (0) | 2022.11.02 |
[ React ] React 기본 ⑨ 컴포넌트 트리에 데이터 공급하기 - Context (0) | 2022.10.23 |
[ React ] React 기본 ⑧ 복잡한 상태 관리 로직 분리하기 - useReducer (0) | 2022.10.22 |
[ React ] React 기본 ⑦ 최적화 - 최적화 완성 (0) | 2022.10.22 |