React 에러 해결 (Cannot read properties of undefined)

Jay·2023년 1월 2일

문제

Cannot read properties of undefined (reading 'userData')

state 상태에 기초하여 map() 메서드로 반복되는 컴포넌트를 렌더링하려 하였으나 다음과 같은 에러가 발생하였다.

원인

state는 비동기적이며 처음 렌더링(마운팅)하기도 전에 동작한다. 이 때에 state가 정의되어있지 않았기 때문에 값은 undefined가 할당된다.
즉, 값이 정의되지 않아 읽을 수 없을 때 발생하는 에러다.

해결

state에 어떤 타입의 값이 들어올 것인지 state의 초깃값에 정의해놓으면 undefined를 방지할 수 있다.

function Component() {
  // useState 괄호 안을 비워놓지 말자
  const [date, setData] = useState();
  
  // useState에 미리 값의 타입을 알려주자
  const [date, setData] = useState([]);
  // 혹은
  const [date, setData] = useState({});
   // 또는
  const [date, setData] = useState("");
   // 타입을 모르겠다면
  const [date, setData] = useState(null);

  return (
   ...
  )
}

출처
https://velog.io/@nemo/react-error-cannot-read-property

0개의 댓글