본문 바로가기
JavaScript/React

[React] #4.1 Rendering the Movies (#코딩공부)

by 함께 공부해요 2020. 6. 8.

https://youtu.be/83hI4VypWK0


<복습>

https://wook-2124.tistory.com/136

 

[React] #4.0 Fetching Movies from API (#코딩공부)

https://youtu.be/bfUC2Iy6jt4 <복습> https://wook-2124.tistory.com/134 https://wook-2124.tistory.com/133 [React] #3.1 All you need to know about State (#코딩공부) https://youtu.be/38I5K3p42WU <복습>..

wook-2124.tistory.com

 

<준비물>

https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com


1. ES6

yts-proxy에서 가져온 movies API를 console.log로 확인해봤다.

 

movie 객체 안의 data.data.movies만 확인해보자. ES6 버젼으로 const movies를 { data } 안(:)의 { data } 안(:)의 { movies }만 가져오는 것으로 표현할 수있고 그러면 console에서 20개의 movies만 따로 볼 수 있다.


2. setState

setState로 state(상태)를 바꿔보자. { movies: movies }movies: []로 정한 stateyts API로 가져온 movies라고 생각하면 된다.

 

movies가 준비가 되면 isLoading을 false state(상태)로 바꿔줘서 "We are ready"가 출력되게 했다.

 

yts API로부터 list_movies.json을 get해오고 state(상태) isLoading이 false가 되면, "Loading..."에서 "We are ready"로 문구가 바뀌는 것을 볼 수 있다.


3. sort_by (DESC 내림차순, ASC 오름차순)

yts API를 sort_by rating으로 desc(내림차순), asc(오름차순)으로도 정렬할 수 있다.

 

API를 가져오는 URL에 sort_by=rating을 추가해서 평점(rating)이 높은 순(DESC)으로 영화가 정리된다.


4. Movies.js

yts API로 가져오는 movies만 render할 Movie.js 파일을 새로 만들고, movies의 propTypes로 prop을 검사하려한다. 그리고 component가 state를 사용하지 않으면 굳이 class component를 사용할 필요없이 function component를 사용하면 된다.

 

yts API movies에 들어있는 id, title(title_long), rating, runtime, genres, summary, poster(medium_cover_image) 가져와보자.

 

Movie propTypes에 number, string, array구분해서 적고 title만 먼저 return해서 rendering(표현)했다.


5. App.js

yts API에서 가져온 movies를 index.html로 render(표현)해주기 위해서 App component에 Movie component를 import했다. 그리고 movies를 render(표현)할 때 this.state.movies로 계속 표현하면 번거로우니, 저번에 isLoading을 this.state.isLoading대신 { isLoading }으로 표현한 것처럼 { movies }로 표현하기 위해 const로 묶어줬다.

 

다음으로 setState로 인해서 isLoading이 false로 바뀌면서 else로 "We are ready" 문구 대신 movies의 개체를 map을 이용해서 Movie prop안에 각각 정의하고 return했다.

 

console.log와 return을 없애고 console을 보니, 각각의 object(개체)의 each child는 unique(유일한) "key" prop을 가져야 한다고 Warning sign이 떴다.

 

때문에 key로써 unique(유일한) 고유 id를 만들었다. 그러나 rating이나 runtime같은 prop은 서로 겹쳐서 unique하지 않을 수도 있다.

 

Warning sign이 없어진 것을 알 수 있다. 오늘은 title만 render했지만 다음 시간엔 나머지 rating, runtime, genres, summary, poster을 모두 render해볼 것 이다.

 

정리: 먼저 yts API로 부터 data(movies)를 async(비동기)로 가져오고, setState를 사용해서 state isLoading=true로 "Loading..."을 먼저 보여준 뒤, data(movies)가 get(fetch, axios)해서 준비가 되면 else isLoading=flasestate가 바뀌면서 화면에 data(movies)를 render(표현)하는 방식이다.

댓글