[react] Data props 넘길 때 에러

jini.choi·2023년 7월 19일
0

react

목록 보기
3/3
post-thumbnail

맛집정보 페이지를 구현하던 중 맵과 슬라이드(이미지) 컴포넌트를 분리하여 props로 RestaurantInfoData 넘겨주었다.

RestaurantInfoData

//RestaurantInfoData.json
{
  "data": {
    "id": 1,
    "title": "회진네 회집",
    "star": "4.9",
    "comments": "Lorem Ipsum is simply dummy text o...",
    "img": [
      { "id": 1, "img": "./images/food1.jpg" },
      { "id": 2, "img": "./images/food2.jpg" },
      { "id": 3, "img": "./images/food3.jpg" }
    ],
    "x": 127.053634,
    "y": 37.5063506
  }
}

RestaurantInfo 컴포넌트

//RestaurantInfo.js

const RestaurantInfo = () => {
  const [RestaurantInfoData, setRestaurantInfoData] = useState([]);

  useEffect(() => {
    fetch('./data/RestaurantInfoData.json')
      .then(res => res.json())
      .then(data => setRestaurantInfoData(data.data));
  }, []);

  return (
    <Style.RestaurantInfoBox>
      <Slide RestaurantInfoData={RestaurantInfoData} />
      <Style.Title>{RestaurantInfoData?.title}</Style.Title>
      <Style.StarRating>
        <Style.Star></Style.Star>
        <span>{RestaurantInfoData?.star}</span>
      </Style.StarRating>
      <Style.Comments>{RestaurantInfoData?.comments}</Style.Comments>

      <Style.MapBox>
        <Map RestaurantInfoData={RestaurantInfoData} />
      </Style.MapBox>
    </Style.RestaurantInfoBox>
  );
};
export default RestaurantInfo;

Map 컴포넌트

const Map = ({ RestaurantInfoData }) => {
  const { kakao } = window;
  const position = new kakao.maps.LatLng(
    RestaurantInfoData?.y,
    RestaurantInfoData?.x,
  );

  const mapContainer = useRef(null);

  useEffect(() => {
    const mapOptions = {
      center: position,
      level: 3, 
    };
   .
   .
   .
    let marker = new kakao.maps.Marker({
      position,
      image: markerImage,
    });
   .
   .
   .
    marker.setMap(map);
  }, []);

  return (
    <div
    .
    .
    .

에러발생

처음에는 지도가 위치에 맞게 떴다가 새로고침만 하면 위치를 못 불러 온다.

원인과 해결방법

useEffect는 마운트가 다 되고나서 랜더링되기 때문이다.
그래서 빈값을 props로 넘겨주기 때문에 Map 컴포넌트에 좌표 데이터가 빈값으로 들어간 것이고 RestaurantInfoData가 변화가 있을 때마다 랜더링해주기 위해서 useEffect 의존성 배열에 RestaurantInfoData를 넣어준다.

Map 컴포넌트

const Map = ({ RestaurantInfoData }) => {
  const { kakao } = window;
  const position = new kakao.maps.LatLng(
    RestaurantInfoData?.y,
    RestaurantInfoData?.x,
  );

  const mapContainer = useRef(null);

  useEffect(() => {
    const mapOptions = {
      center: position,
      level: 3, 
    };
   .
   .
   .
    let marker = new kakao.maps.Marker({
      position,
      image: markerImage,
    });
   .
   .
   .
    marker.setMap(map);
  }, [RestaurantInfoData]); //수정

  return (
    <div
    .
    .
    .

결과 화면

😓 반성

useEffect 와 React Component가 랜더링 되는 시점에 대해 먼저 생각을 했다면 헤매지 않았을 것 같다.

profile
개발짜🏃‍♀️

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

정말 유익한 글이었습니다.

답글 달기