• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

무한 루프 에러 질문드립니다.!

23.11.12 21:22 작성 조회수 369

0

import React, { useState, useEffect, useContext, useRef } from "react";
import { useNavigate } from "react-router-dom";

import axios from "axios";
import { BbsSettingContext } from "../common/Board";
import ToastEditor from "../component/ToastEditor";
import MyButton from "../common/ComButton";

const BoardView = ({ postId }) => {
  const titleInputRef = useRef();
  const contentsAreaRef = useRef();
  const toastEditorRef = useRef(); // ToastEditor의 ref

  const [post, setPost] = useState({
    nttSj: "",
    nttCn: "",
    regDate: "",
  });
  const [boardSetting, setBoardSetting] = useState(null);
  const boardSetData = useContext(BbsSettingContext);
  const Navigate = useNavigate();
  const formatDate = (timestamp) => {
    const date = new Date(timestamp);
    const options = { year: "numeric", month: "long", day: "numeric" };
    return date.toLocaleDateString("ko-KR", options);
  };

  useEffect(() => {
    if (boardSetData) {
      setBoardSetting(boardSetData);
      axios
        .get(`http://localhost:8080/board/${boardSetData.bbsId}/post/${postId}`)
        .then((response) => {
          setPost({
            nttSj: response.data.post.nttSj,
            nttCn: response.data.post.nttCn,
            regDate: response.data.post.regDate,
          });
        })
        .catch((error) => console.log(error));
    }
  }, [post]);
  return (
    <div className="BoardView">
      <div className="upInfoArea">
        <div type="text" name="boardTitle" className="titleDiv">
          {post.nttCn}
        </div>
        <div type="text" name="regId" className="regIdDIv">
          {formatDate(post.regDate)}
        </div>
      </div>
      <div className="contentArea">
        <div className="contentsText">{post.nttCn}</div>
      </div>
      <section>
        <div className="btnArea">
          <MyButton text={"리스트이동"} onClick={() => Navigate(-1)} />
          <MyButton text={"수정하기"} type="positive" />
        </div>
      </section>
    </div>
  );
};

export default BoardView;

질문이 있는데 useEffect에서 [post]로 하면 무한 루프가 돌고 저런식으로 [boardSetData,post.postId,post.nttSj,post.nttCn] 으로 놓으면 무한루프가 돌지 않는데 이유를 알수 있을까요 ...

postId는 글번호 nttSj 제목 , nttCn 제목이며
const boardSetData = useContext(BbsSettingContext);
여기서 boardSetData는 게시판 셋팅 데이터 입니다 .왜 무한 루프가 도는지 알수있을까요 .

게시판 셋팅 , 글제목, 글번호 글내용이 바뀌면 useEffect의 axios가 전송 되어야 하게 할려고 합니다 근데 무한 루프가 도네요 ...

답변 1

답변을 작성해보세요.

0

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

우선 강의중에 진행하는 코드가 아닌걸로 보이네요 ㅠㅠ 죄송하지만 이런 경우 제가 프로젝트 전체 파일을 직접 받아 코드를 리뷰해 봐야 정확한 원인을 확인할 수 있습니다.

일단 현재 보내주신 코드로만 보았을 때에는 useEffect 내에서 setPost를 호출하여 post State를 업데이트 하고 있는걸로 보이는데요, 이때 useEffect의 deps를 [post]로 설정하시면 당연히 무한루프가 돌게 됩니다.

더 자세히 말씀드리면 다음과 같습니다.

  1. post값이 변경되어 useEffect가 실행됨

  2. useEffect에서 post를 또 수정함

  3. 1번 반복

감사합니다.