강의

멘토링

로드맵

Inflearn Community Q&A

wnsvy44755710's profile image
wnsvy44755710

asked

Learn React by Building It: Basics

TypeError: Cannot read properties of null (reading 'includes') 에러가 뜹니다.

Written on

·

10K

1

react-dom.production.min.js:189 TypeError: Cannot read properties of null (reading 'includes')

강의 36. create-react-app으로 만든 앱 배포하기에서 다음과 같은 에러가 뜹니다.

includes는 아래에서만 1회 사용하였습니다.

const alreadyFavorite = favorites.includes(mainCat);

 

javascriptreact

Answer 1

0

jayjinjay님의 프로필 이미지
jayjinjay
Instructor

Cannot read properties of null (reading 'includes')

 

가 뜻하는 바는

변수.includes를 했는데 변수가 null이라서 null에는 includes가 없어서 에러가 났다는 뜻이에요.

 

image

160line 에서 console.log(favorites)를 하면 null이 들어가있을거예요.

 

158line에서 favorites를 초기화하는 코드가 로컬스토리지에서 읽어오는 방식인데,

로컬스토리지에 값이 없으면 null을 반환하기 때문에 코드가 이렇게 깨졌을 거예요.

favorites의 기본값을 []로 줘보시겠어요?

 

const [favorites, setFavorites] = useState(() => { return jsonLocalStorage.getItem('favorites') || []; });

 

wnsvy44755710's profile image
wnsvy44755710

asked

Ask a question