AI기록장
React_기초다지기_하루정리(useReducer) 본문
◼︎React
⚑목표 : 실습 기초 세팅
- 상태 관리 세팅하기
: 프로젝트 전반적으로 사용될 일기 데이터 state관리 로직 작성하기 - 프로젝트 State Context세팅하기
: 일기 데잍 State를 공급할 context를 생성하고 Provider로 공급하기 - 프로젝트 Dispatch Context 세팅하기
: 일기 데이터 Statedml Dispatch 함수들을 공급할 Context를 생성하고 Provider로 공급하기
import React, { useReducer, useRef } from "react";
import "./App.css";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./pages/Home";
import Edit from "./pages/Edit";
import New from "./pages/New";
import Diary from "./pages/Diary";
const reducer = (state, actions) => {
let newState = [];
switch (actions.type) {
case "INIT": {
return actions.data;
}
case "CREATE": {
newState = [actions.data, ...state];
break;
}
case "REMOVED": {
newState = state.filter((it) => it.id !== actions.targetId);
break;
}
case "EDIT": {
newState = state.map((it) =>
it.id === actions.data.id ? { ...actions.data } : it
);
break;
}
default:
return state;
}
return newState;
};
export const DiaryStateContext = React.createContext();
export const DiaryDispatchContext = React.createContext();
function App() {
const [data, dispatch] = useReducer(reducer, []);
const dataId = useRef(0); // id를 만들어줌
//정보를 파라미터로받아서 객체로 만들고 그것을 creat로 저장함
const onCreate = (date, content, emotion) => {
dispatch({
type: "CREATE",
data: {
id: dataId.current,
date: new Date(date).getTime(),
content,
emotion,
},
});
dataId.current += 1;
};
const onRemove = (targetId) => {
dispatch({ type: "REMOVE", targetId });
};
const onEdit = (targetId, date, content, emotion) => {
dispatch({
type: "EDIT",
data: {
id: targetId,
date: 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="/edit" element={<Edit />} />
<Route path="/diary/:id" element={<Diary />} />
</Routes>
</div>
</BrowserRouter>
</DiaryDispatchContext.Provider>
</DiaryStateContext.Provider>
);
}
export default App;
//클라이언트 사이드 랜더링 기법을 이용함
- 이번 페이지는 크게 설명할꺼는 없지만, 저번시간의 코드들을 useReducer을 이용해서 코드 업데이트를 했다!
// 아직 useReducer을 사용하는데 있어 낯선감이 있어, 아직 코드의 관계를 빠르게 이해를 못하겠다!
이부분은 useReducer을 한번 더 이해하고, 각각의 프롭스의 관계를 다시 정리해봐야겠다.
'React' 카테고리의 다른 글
React_기초다지기_하루정리(util 폴더 이용하기, useNavigate, 특정 객체에 대한 처리 실습) (0) | 2023.06.22 |
---|---|
React_기초다지기_하루정리(new Date(), sortType-Compare, 이미지를 이용한 마크업) (2) | 2023.06.05 |
React_기초다지기_하루정리(font인용, 공용컴퍼넌트 생성,) (3) | 2023.06.01 |
React_기초다지기_하루정리(React Router) (0) | 2023.06.01 |
React_기초다지기_하루정리(복잡한 상태변화 로직 분리 - useReduce) (0) | 2023.05.31 |