• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 React 게시판 리액트로 달력을 만들어봤는데 달 변경에 문제가 있습니다.

리액트로 달력을 만들어봤는데 달 변경에 문제가 있습니다.

  • 이 주제에는 3개 답변, 2명 참여가 있으며 SEO1 년, 7 월 전에 전에 마지막으로 업데이트했습니다.
4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 글쓴이
  • #108369

    SEO
    참가자
    function TimeLineCalendar({ nowCal, setNowCal }) {
      const [currentDate, setCurrentDate] = useState(new Date());
      const [count, setCount] = useState(0);
      const changeMonth = (amount) => {
        setCurrentDate((prevDate) => {
          const newDate = new Date(prevDate);
          newDate.setMonth(newDate.getMonth() + amount);
          return newDate;
        });
      };
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth();
      const firstDay = new Date(year, month, 1);
      const lastDay = new Date(year, month + 1, 0);
      const daysInMonth = lastDay.getDate();
      const startDay = firstDay.getDay();
      const endDay = lastDay.getDay();
      const prevCalendar = [];
      const calendar = [];
      const nextCalendar = [];
      const remainCalendar = [];
      const prevMonthDays = startDay > 0 ? new Date(year, month, 0).getDate() : 0;
      for (let i = startDay - 1; i >= 0; i--) {
        prevCalendar.push({ date: prevMonthDays - i});
      }
      for (let i = 1; i <= daysInMonth; i++) {
        calendar.push({ date: i, isCurrentMonth: true, id: i });
      }
      const nextMonthDays = 6 - endDay;
      for (let i = 1; i <= nextMonthDays; i++) {
        nextCalendar.push({ date: i});
      }
      const remainingDays = 42 - calendar.length - prevCalendar.length - nextCalendar.length;
      for (let i = 1; i <= remainingDays; i++) {
        const nextMonthDate = new Date(year, month + 1, nextMonthDays + i).getDate();
        remainCalendar.push({date: nextMonthDate});
      }
      return (
        <div style={{marginLeft:'30px'}}>
          <div style={{width:'290px', display:'flex', justifyContent:'space-between'}}>
            <div className='fs-16 regular'>{`${year}년 ${month + 1}월`}</div>
            <div style={{display:'flex'}}>
              <div onClick={()=>{
                if(count == 0 || count == 1) {
                  changeMonth(-1);
                  setCount(val => val - 1)
                }
              }} style={{marginRight:'36px', cursor:'pointer'}}><ChangeMo color={count == -1 ? '#949494' : '#222222'}/>
              </div>
              <div onClick={()=>{
                if(count == 0 || count == -1) {
                  changeMonth(1);
                  setCount(val => val + 1)
                }
              }} style={{transform:'rotateY(180deg)', cursor:'pointer'}}><ChangeMo color={count == 1 ? '#949494' : '#222222'}/>
              </div>
            </div>
            
          </div>
          <div style={{display:'grid', gridTemplateColumns:'repeat(7, 36px)', gridAutoRows: '36px', gridColumnGap:'6px', gridRowGap:'9px', textAlign:'center', alignItems:'center', marginTop:"20px"}} className='fs-14'>
            {['일', '월', '화', '수', '목', '금', '토'].map((day) => (
              <div key={day} style={{margin:"20px 0 28px 0", color:'#494949'}}>
                {day}
              </div>
            ))}
            {prevCalendar.map((item, index) => {
                return (
                    <div className='fc-94' key={index}>
                        {item?.date}
                    </div>
                )})}
            {calendar.map((item, index) => {
                return (
                    <div key={index} className='date' onClick={()=>{
                      console.log(nowCal)
                      setNowCal([year, month, item.id])
                      }}>
                        <div style={{width:'36px', height:'36px', display:'flex', alignItems:'center', borderRadius:'6px', cursor:'pointer'}} className={index==nowCal[2]-1 && year==nowCal[0] && month==nowCal[1] ? styles.toDay : styles.notToday}>
                          <div style={{margin:'0 auto'}}>
                            <span className={index==nowCal[2]-1 && year==nowCal[0] && month==nowCal[1] ? 'fc-white' : ''}>{item?.date}</span>
                          </div>
                        </div>
                    </div>
                )})}
            {nextCalendar.map((item, index) => {
                return (
                    <div className='fc-94' key={index}>
                        {item?.date}
                    </div>
                )})}
            {remainCalendar.map((item, index) => {
                return (
                    <div className='fc-94' key={index}>
                        {item?.date}
                    </div>
                )})}
          </div>
        </div>
      )
    }
    
    달력을 렌더링하고 컴포넌트 버튼을 통해 changeMonth 함수를 실행시켜 달력이 바뀌는데
    저 상태에서 
    처음 렌더링 된 이후 이전달 버튼을 한번 누르면 작동을 안 하고 두번 이상 눌러야 그때부터
    제대로 동작합니다. 그리고 처음 렌더링 됐을 때 다음달 버튼을 누른다면 첫번째는 의도대로 작동하지만
    두번째 누를 시 갑자기 2개월이 넘어가버리고 그 후부터 의도대로 달력이 움직입니다.
    어느 부분에서 이런 오류가 발생하는 걸까요?
    #108385

    codingapple
    키 마스터
    count변수가 이상해서 그럴수도요 
    if문이나 count변수 의도대로 동작하고 있는지 출력해봅시다
    #108392

    SEO
    참가자
    if문이랑 count 변수를 전부 지우고 클릭시 changMonth 함수만 실행시켜도 
    동일한 문제가 나타납니다.
    
    useEffect도 써보고 여러 방면에서 시도해봤는데 해결이 되질 않습니다.
    
     
    #108400

    SEO
    참가자
    24년이 되니까 왠지 모르게 고쳐졌슴다
    대체 왜...
4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠