한입리액트 섹션 6 - 페이지 구현 - 홈(/) 코드
// Home.js
import { useState, useContext, useEffect } from "react";
import { DiaryStateContext } from "../App";
import MyButton from "./../components/MyButton";
import MyHeader from "./../components/MyHeader";
import DiaryList from "./../components/DiaryList";
const Home = () => {
const diaryList = useContext(DiaryStateContext);
const [data, setData] = useState([]);
const [curDate, setCurDate] = useState(new Date());
const headText = `${curDate.getFullYear()}년 ${curDate.getMonth() + 1}월`;
useEffect(() => {
if (diaryList.length >= 1) {
const firstDay = new Date(
curDate.getFullYear(),
curDate.getMonth(),
1
).getTime();
const lastDay = new Date(
curDate.getFullYear(),
curDate.getMonth() + 1,
0
).getTime();
setData(
diaryList.filter((it) => firstDay <= it.date && it.date <= lastDay)
);
}
}, [diaryList, curDate]);
useEffect(() => {
console.log(data);
}, [data]);
const increaseMonth = () => {
setCurDate(
new Date(curDate.getFullYear(), curDate.getMonth() + 1, curDate.getDate())
);
};
const decreaseMonth = () => {
setCurDate(
new Date(curDate.getFullYear(), curDate.getMonth() - 1, curDate.getDate())
);
};
return (
<div>
<MyHeader
headText={headText}
leftChild={<MyButton text={"<"} onClick={decreaseMonth} />}
rightChild={<MyButton text={">"} onClick={increaseMonth} />}
/>
<DiaryList diaryList={data} />
</div>
);
};
export default Home;
// DiaryList.js
import { useState } from "react";
const sortOptionList = [
{ value: "latest", name: "최신순" },
{ value: "oldest", name: "오래된 순" },
];
const ControlMenu = ({ value, onChange, optionList }) => {
return (
<select value={value} onChange={(e) => onChange(e.target.value)}>
{optionList.map((it, idx) => (
<option key={idx} value={it.value}>
{it.name}
</option>
))}
</select>
);
};
const DiaryList = ({ diaryList }) => {
const [sortType, setSortType] = useState("lastest");
return (
<div>
<ControlMenu
value={sortType}
onChange={setSortType}
optionList={sortOptionList}
/>
{diaryList.map((it) => (
<div key={it.id}>{it.content}</div>
))}
</div>
);
};
DiaryList.defaultProps = {
diaryList: [],
};
export default DiaryList;
// App.js
import React, { useReducer, useRef } from "react";
import "./App.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import New from "./pages/New";
import Edit from "./pages/Edit";
import Diary from "./pages/Diary";
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;
}
default:
return state;
}
return newState;
};
export const DiaryStateContext = React.createContext();
export const DiaryDispatchContext = React.createContext();
const dummyData = [
{
id: 1,
emotion: 1,
content: "오늘의일기 1번",
date: 1704809815768,
},
{
id: 2,
emotion: 2,
content: "오늘의일기 2번",
date: 1704809815769,
},
{
id: 3,
emotion: 3,
content: "오늘의일기 3번",
date: 1704809815770,
},
{
id: 4,
emotion: 4,
content: "오늘의일기 4번",
date: 1704809815771,
},
{
id: 5,
emotion: 5,
content: "오늘의일기 5번",
date: 1704809815772,
},
];
function App() {
const [data, dispatch] = useReducer(reducer, dummyData);
console.log(new Date().getTime());
const dataId = useRef(0);
// CREATE
const onCreate = (date, content, emotion) => {
dispatch({
type: "CREATE",
data: {
id: dataId.current,
date: 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: 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;
해당 강의 23분경부터 계속 막힙니다.


아무리 정렬을 바꿔도 정렬이 변경되지 않아요. 따라친다고 따라쳤는데 어디가 틀린지 잘 모르겠습니다.
답변 1
0
안녕하세요 이정환입니다.
올려주신 코드를 확인해보니
현재 DiaryList 컴포넌트에 정렬관련 기능이 존재하지 않는것으로 보이는데요
(아마 정렬 토글만 만들어 두신 상태인것 같습니다)
해당 강의의 24분 경을 확인하셔서 정렬 기능을 끝까지 구현하시기 바랍니다.
PS. 앞으로는 질문 가이드라인대로 CodeSandBox나 GitHub를 통해 코드 보내주시면 감사하겠습니다.
감사합니다 새해복 많이받으세요 🙇♂
Editor Component의 최적화 불가능 이슈
0
37
2
useCallback ⊂ useMemo
0
34
2
라이브러리 설치 질문
0
33
2
linter 질문
0
40
2
감정일기장 vercel 배포 후 새로 고침 시 404페이지가 뜨는 이유
0
40
2
Sort 메서드 관련 아티클
0
43
2
4.1) React.js를 소개합니다 강의를 듣고 궁금한 점이 생겼습니다.
0
45
2
html, body에 적용하는 css 스타일 질문입니다.
0
38
2
eslint.config.js 설정 질문입니다.
0
90
2
존재하지 않는 일기 url입력 시 alert이 두 번 떠요
0
66
1
교재(3쇄)와 강의 내용 문의
0
65
2
12.13) 하단 여백 스타일링 관련 질문 드립니다.
0
87
2
에러 질문드립니다
0
104
2
VSCode 설정 문의
0
137
2
PPT 코드 관련 질문
0
66
2
useEffect와 lifecycle문의
0
87
2
프론트엔드 학습 수준 문의
0
107
2
리액트 챕터별 코드에서 eslint 설정파일이 없어요
0
110
2
데이터 로딩중 화면만 계속 나와요!!
0
100
2
퍼블리셔일경우 어느정도 수준까지 강의를 들어야할까요
0
129
2
이후의 커리큘럼 문의
0
151
2
실슬환경 설정에서 save후 console.log 부분이 새로고침이 안되는현상입니다.
0
106
2
최적화 관련 질문있습니다 (useMemo 등)
0
126
3
프로바이더 컴포넌트의 위치는 어떤 기준인가요?
1
124
3





