[React] Movie app clone coding : List with .map
2-3. List with .map
앞서 리스트를 만든 방법은 효율성이 떨어지므로 갖고 있는 영화 정보의 양에 관계없이 이를 토대로 리스트를 만든다.
API에서 가져온 영화 정보를 불러올 때 Array
를 만든다.
리스트에는 여러 object가 있다. (ex) title
, poster
아래와 같이 영화정보를 array로 만들 수 있다.
1// App.js
2 ...
3const movies = [
4 {
5 title: "Matrix",
6 poster: "https://displate.com/displates/2016-09-30/60a3501bd3167cf9330acef43ab51ab3.jpg?w=280&h=392"
7 },
8 {
9 title: "Full Metal Jacket",
10 poster: "https://cf5.s3.souqcdn.com/item/2016/05/17/10/74/99/15/item_XL_10749915_14378548.jpg"
11 },
12 {
13 title: "Oldboy",
14 poster: "https://posterspy.com/wp-content/uploads/2016/02/Oldboy-by-Clay-Disarray-oct.jpg"
15 },
16 {
17 title: "Start Wars",
18 poster: "http://aidanmoher.com/blog/wp-content/uploads/2011/01/Olly-Moss-Star-Wars.jpeg"
19 }
20
21]
22 ...
이제 정렬된 array를 보면서 최종 리스트를 만든다.
array
는 map
이라는 기능이 있다. map
은 사용자가 제공한 기능/명령의 결과값을 array로 만든다.
*참고 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
movies
는 array
이다. 그 다음 map
기능을 통해 새로운 array
를 만든다.
1// App.js
2 ...
3class App extends Component {
4 ...
5 return (
6 <div className="App">
7 {movies.map(movie => {
8 return <Movie title={movie.title} poster={movie.poster} />
9 })}
10 </div>
11 ...
12}
13 ...
정리하면, 이 작업은 movies
array를 가져다가 해당 movies array
안의 element를 활용해서 mapping
해서 새로운 component
를 만드는 것이다. 해당 array
의 element
를 토대로 한 component
인 것이다.
💡movies array를 활용한다는 것이 포인트.
map() syntax
1var new_array = arr.map(function callback(currentValue[, index[, array]]) {
2 // Return element for new_array
3}[, thisArg])
currentValue
값에 들어가는 것이 movies
array 이다.
map으로 작업한 것을 코드로 표현해보면 아래와 같다. 즉, 아래 두 코드는 같은 결과의 코드이다.
1// mapping
2{movies.map(movie => {
3 return <Movie title={movie.title} poster={movie.poster} />
4})}
1// 위 코드를 풀어서 표현
2{[
3 <Movie title={movies[0].title} poster={movies[0].poster} />
4 <Movie title={movies[1].title} poster={movies[1].poster} />
5 <Movie title={movies[2].title} poster={movies[2].poster} />
6 <Movie title={movies[3].title} poster={movies[3].poster} />
7]}
전체코드
1// App.js
2import React, { Component } from 'react';
3import './App.css';
4import Movie from './Movie';
5
6const movies = [
7 {
8 title: "Matrix",
9 poster: "https://displate.com/displates/2016-09-30/60a3501bd3167cf9330acef43ab51ab3.jpg?w=280&h=392"
10 },
11 {
12 title: "Full Metal Jacket",
13 poster: "https://cf5.s3.souqcdn.com/item/2016/05/17/10/74/99/15/item_XL_10749915_14378548.jpg"
14 },
15 {
16 title: "Oldboy",
17 poster: "https://posterspy.com/wp-content/uploads/2016/02/Oldboy-by-Clay-Disarray-oct.jpg"
18 },
19 {
20 title: "Start Wars",
21 poster: "http://aidanmoher.com/blog/wp-content/uploads/2011/01/Olly-Moss-Star-Wars.jpeg"
22 }
23
24]
25
26class App extends Component {
27 render() {
28 return (
29 <div className="App">
30 {movies.map(movie => {
31 return <Movie title={movie.title} poster={movie.poster} />
32 })}
33 </div>
34 );
35 }
36}
37
38export default App;