• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

diaryList 날짜 필터 관련

23.06.23 21:07 작성 조회수 461

0

안녕하세요. 저는 현재 "페이지구현-홈(/)" 강의 18분 쯔음 까지 들었습니다.

Home 컴포넌트에서 filter 를 사용하여 현재 날짜에만 dummyList 로 작성해둔 일기가 떠야하는데 뜨질 않습니다.

import { DiaryStateContext } from "./App";
import MyButton from "./components/MyButton";
import MyHeader from "./components/MyHeader";
import { useContext, useEffect, useState } from "react";
import DiaryList from "./components/DiaryList";

const Home = () => {

  const diaryList = useContext(DiaryStateContext); //dummyList 를 받음

  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(); //현재 년, 월의 1일의 시간을 구함

      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)
    console.log(diaryList)
  },[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
        leftChild={<MyButton text={"<"} onClick={decreaseMonth} />}
        headText={headText}
        rightChild={<MyButton text={">"} onClick={increaseMonth} />}
      />
      <DiaryList diaryList={data}/>
    </div>
  );
}
export default Home;

이게 제 Home 컴포넌트이고, 중간에 보면 useEffect 로 data 와 diaryList 를 출력했을때 data 는 빈 배열로 출력되고 diaryList 는 제가 App.js 에서 dummyList 로 작성한 데이터가 잘 출력됩니다.
아무리 봐도 어디가 잘못된건지 모르겠습니다. ㅜㅜ
날짜가 잘못된건가 싶어 new Date() 로 다시 확인해봐도 현재 날짜로 잘 나옵니다

이건 useEffect 로 출력한 콘솔창 입니다.

답변 2

·

답변을 작성해보세요.

1

Jaeyoung Jo님의 프로필

Jaeyoung Jo

2023.07.31

App.js의 useReducer(reducer,dummyData)부분이

App.js의 useReducer(reducer,[dummyData])

로 되어있진 않은지 확인해보세요.

Array(5)데이터가 다시 한번 더 배열에 쌓여있네요 ^^

로 변경하세요.

Ryan Nam님의 프로필

Ryan Nam

2023.08.25

감사합니다

0

안녕하세요 이정환입니다.

질문 공지사항에 적어두었듯 하나의 파일만으로는 정확한 오류 원인 분석이 어렵습니다 😢

따라서 현재 오류가 발생하는 코드를 깃허브나 코드샌드박스에 업로드하신 뒤 공유해주시면 살펴보겠습니다.