[+35]ComponentDidMount뒤에 render시키기

AeRi Lee·2020년 3월 2일
0

mock-data를 이용해서 componentDidMount에 fetch를 시켜서 render를 시키려고 했는데 문제가 발생했다.

mock data에서 fetch로 가져올 정보는 이 product였고


componentDidMount에 fetch를 시켜줬다.

render되는 곳에

{this.state.product.product_color}
를 map 돌려주려고 했는데 에러가 났다.

그 이유인 즉슨,
componentDidMount는 한번 render를 돌고 난 뒤 도는데 그 전에 product의 product_color를 쓰려고 하니 없어서 에러가 나타나는 것 이었다!

그래서 5기 분들의 도움을 받아서 방법을 찾아낸 것이

이렇게 return 앞에 조건문을 달아주는 것이다.
조건에 따라 return이 다르게 되는 것이다.
그러면 처음에 this.state.product.product_color가 null이니까 null이 return되고 나서 componentDidMount를 돌고 새 return을 돌게 되는 것이다.

이 방법은 앞으로도 유용하게 쓰일 것이라고 하셨다!

++++ 이 방법 만으로는 나타나지 않는 경우가 있었는데.... 밑으로.


삼항 연산자 이용하기

간단한 코드로 실험해보는 과정에서 if문을 써도 property 0이 undefined라는 오류가 났다.

이 방법 또한 fetch되어 state가 새로 생긴 뒤에 그 값들을 이용하기 위해 사용되는 방법이다.

return 되는 곳에서 this.state.data.categories가 필요한데 있는지 없는지 모르겠고 들어왔을 때 뜨면 좋겠다고 생각한다면,

this.state.data.categories
? this.state.data.categories.name
: ""

라고 적으면
this.state.data.categories가 있다면
this.state.data.categories.name을 쓰고
없다면 빈 결과 ""를 보여 주겠다는 식이다.

이렇게 하니 this.state.data 의 name property가 0 이라는 오류에서 벗어날 수 있었다.

profile
👩🏻‍💻 Junior Web Frontend Developer

0개의 댓글