해결된 질문
작성
·
168
0
// 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를 통해 코드 보내주시면 감사하겠습니다.
감사합니다 새해복 많이받으세요 🙇♂
헉 질문 가이드라인을 못 봤습니다. 집에 가서 시도해보도록 할게요!
감사합니다 새해 복 많이 받으세요!