[Reactjs] cannot read properties of undefined on props

SMongS·2022년 8월 6일
0

React

목록 보기
1/1

부모 파일에서 받은 데이터를 자식 파일로 넘길 때, 정의가 되지 않았다는 에러가 떴습니다.

부모 페이지

const ParentPage: FC<ParentProps> = () => {
  const [ data, loading, error ] = DB로 요청보내는 함수;
  return (
    <>
      <div>
        // 자식 페이지로 data 객체 전달
        <ChildPage data={data} />
      </div>
    </>
  );
};

export default ParentPage;

자식 페이지

const ChildPage: FC<ChildProps> = ({ data }) => {
  const { user, content } = data;
  return (
    <div>
      <div>
        {content}
      </div>   
      <div>
        <Writer
          imgUrl={user.profileImageUrl}
          userName={user.nickname}
        />
      </div>
    </div>
  );
};

이렇게 data를 보내면 ChildProps(ChildPage)에서cannot read properties of undefined on props 에러가 납니다.

이 에러가 undefined를 자식 페이지에게 전달하기 때문인 것 같습니다.

데이터가 먼저 도착해서 충돌을 한 것 같습니다.

즉, 자식 props가 데이터를 인자로 넘겨 받는데, 자식 props와 부모 props가 동시에 실행되다 보니 자식 props가 인자를 넘겨 받기도 전에 실행되서 넘겨 받는 데이터가 확인이 안되서 에러가 발생하는 것 같습니다.

그래서 자식 props가 인자를 제대로 넘겨 받는지 대기하고 받은 후에 렌더링하도록 하면 됩니다.

그렇다면 부모에서 확인을 하고 보내면 되기에

{data?.user? 
  <PostContent data={data} />
  : <p>No data here</p>
}

data? 가 data가 제대로 넘겨 받았는지 확인을 하고 보내는 방식입니다.
많약 없다면 삼항연산자로 인해 다른 코드가 반환합니다.

profile
반갑습니당~😄

0개의 댓글