본문 바로가기
React/ReactJS로 영화 웹 서비스 만들기

6. 리액트 영화 앱 만들기

by 닉우 2020. 8. 8.

<영화 API 사용해보기>

axios를 import한 다음, componentDidMount() 함수에서 axios로 API를 호출하면 된다.

axios는 네트워크를 사용해서 느리게 동작하므로 getMovies 함수를 만들고,

그 함수안에서 axios.get()이 실행되로록 만든다.

그리고 async, await를 사용해서 자바스크립트에게 getMovies()함수는 시간이 좀 필요하다는것을 알린다.

 

this.setState에 key:value 와 isLoading의 상태를 업데이트 해준다.

하지만 아직 화면에는 아래와 같은 메시지만 뜰거다.

그 이유는 movies state를 Movie컴포넌트를 통해 화면에 그려야 한다.

 


<코드기록>

import React from 'react';
import axios from 'axios';

class App extends React.Component {
	state = {
		isLoading: true,
		movies: []
	};
	getMovies = async () => {
		const { data: { data: { movies } } } = await axios.get('https://yts-proxy.now.sh/list_movies.json');
		this.setState({ movies, isLoading: false });
	};
	componentDidMount() {
		this.getMovies();
	}

	render() {
		const { isLoading } = this.state;
		return <div> {isLoading ? 'Loading...' : 'We are ready'} </div>;
	}
}

export default App;

<Movie 컴포넌트 만들기>

 

Movie에 넘어와야 하는 영화 데이터를 정의하고 관리하기 위해

prop-types를 사용할거다.

 

import React from 'react';
import PropTypes from 'prop-types';

function Movie(){
    return <h1></h1>;
}

Movie.propTypes = {
    id: PropTypes.number.isRequired,
    year: PropTypes.number.isRequired,
    title: PropTypes.string.isRequired,
    summary: PropTypes.string.isRequired,
    poster: PropTypes.string.isRequired,
};

export default Movie;


※ poster에는 영화 포스터 이미지 주소를 저장할거다.


<API 정렬 기능 사용하기>

 

sort_by 기능으로 영화 데이터를 정렬 할 수 있다.

평점순으로 정렬을 할것이다.

 

Movie 컴포넌트가 이 props를 받아 출력할 수 있도록 Movie 컴포넌트를 마저 완성해 보자.

 

일단 영화 title만 출력되도록 할거다. (컴포넌트는 map()함수로 출력)

 

<코드기록>

 

<App.js>

import React from "react";
import axios from "axios";
import Movie from "./Movie";

class App extends React.Component {
  state = {
    isLoading: true,
    movies: [],
  };
  getMovies = async () => {
    const {
      data: {
        data: { movies },
      },
    } = await axios.get(
      "https://yts-proxy.now.sh/list_movies.json?sort_by=rating"
    );
    this.setState({ movies, isLoading: false });
  };
  componentDidMount() {
    this.getMovies();
  }

  render() {
    const { isLoading, movies } = this.state;
    return (
      <div>
        {" "}
        {isLoading
          ? "Loading..."
          : movies.map((movie) => {
              console.log(movie);
              return (
                <Movie
                  key={movie.id}
                  id={movie.id}
                  year={movie.year}
                  title={movie.title}
                  summary={movie.summary}
                  poster={movie.medium_cover_image}
                />
              );
            })}{" "}
      </div>
    );
  }
}

export default App;

<Movie.js>

import React from "react";
import PropTypes from "prop-types";

function Movie({ id, title, year, summary, poster }) {
  return <h4>{title}</h4>;
}

Movie.propTypes = {
  id: PropTypes.number.isRequired,
  year: PropTypes.number.isRequired,
  title: PropTypes.string.isRequired,
  summary: PropTypes.string.isRequired,
  poster: PropTypes.string.isRequired,
};

export default Movie;

<실행화면>


<영화 앱 스타일링 하기 - 기초 >

 

우선 App 컴포넌트, Movie 컴포넌트에 HTML을 추가할 거다.

JSX의 가장 바깥쪽은 section 엘리먼트로 감싼다.

Loading부분과 Movie 컴포넌트들은 div 엘리먼트로 감싼다.

 

<코드기록>

 

<App.js>

import React from "react";
import axios from "axios";
import Movie from "./Movie";

class App extends React.Component {
  state = {
    isLoading: true,
    movies: [],
  };
  getMovies = async () => {
    const {
      data: {
        data: { movies },
      },
    } = await axios.get(
      "https://yts-proxy.now.sh/list_movies.json?sort_by=rating"
    );
    this.setState({ movies, isLoading: false });
  };
  componentDidMount() {
    this.getMovies();
  }

  render() {
    const { isLoading, movies } = this.state;
    return (
      <section class="container">
        {isLoading ? (
          <div>
            <span class="loader__text">Loading...</span>
          </div>
        ) : (
          <div class="movies">
            {movies.map((movie) => (
              <Movie
                key={movie.id}
                id={movie.id}
                year={movie.year}
                title={movie.title}
                summary={movie.summary}
                poster={movie.medium_cover_image}
              />
            ))}
          </div>
        )}
      </section>
    );
  }
}

export default App;

<Movie.js>

import React from "react";
import PropTypes from "prop-types";

function Movie({ id, title, year, summary, poster }) {
  return (
    <div>
      <h3 class="movie__data">{title}</h3>
      <h5 class="movie__title">{year}</h5>
      <p class="movie__summary">{summary}</p>
    </div>
  );
}

Movie.propTypes = {
  id: PropTypes.number.isRequired,
  year: PropTypes.number.isRequired,
  title: PropTypes.string.isRequired,
  summary: PropTypes.string.isRequired,
  poster: PropTypes.string.isRequired,
};

export default Movie;

<포스터 이미지 추가하기 & CSS >

 


CSS파일을 생성하고 임포트 해보자.

 

App.css 파일만 배경색을 어둡게 수정해 보자.


<실행화면>

 


 

 

 

 

 

 

 

 

 

 

※ 본 포스팅은 개인 공부 기록을 목적으로 남긴 글이며 본 사실과 다른 부분이 있다면 과감하게 지적 부탁드립니다.

댓글