관리 메뉴

프로그래밍 삽질 중

[인프런 강의]리액트 무비앱 시리즈4 - MovieDetail(1) 본문

과거 프로그래밍 자료들/React

[인프런 강의]리액트 무비앱 시리즈4 - MovieDetail(1)

평부 2022. 5. 17. 17:14

* 인프런 '따라하며 배우는 노드, 리액트 시리즈 - 영화 사이트 만들기' 내용 정리

* The Moive DB API 이용 (사이트 : https://www.themoviedb.org/)

* The Moive DB API 관련 설명 - 영어(사이트 : https://developers.themoviedb.org/3/getting-started/images)

* 회원가입/로그인/인증한 페이지에 이 부분 넣을 예정

(정리한 글 : https://ba-gotocode131.tistory.com/category/%EA%B0%9C%EC%9D%B8%EA%B3%B5%EB%B6%80/%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8)

 

 

[API 이용해서 MovieDetail에 정보 넣기]

1. LandingPage -> MovieDetail로 이동하기

2. MovieDetail에서 메인이미지 항목 만들기(LandingPage/Sections/MainImage.js)

3. MovieInfo에서 상세정보 항목 만들기(MovieDetail/Section/MovieInfo.js)

4. MovieDetail로 MovieInfo 가져오기

5. 구글 크롬에서 확인하기

 

 

 

1. LandingPage -> MovieDetail로 이동하기

import React, { useEffect, useState } from "react";
import { API_URL, API_KEY, IMAGE_BASE_URL } from "../../../Config";
import MainImage from "./Sections/MainImage";
import GridCards from "../commons/GridCards";
import { Row } from "antd";

function LandingPage() {
  // const navigate = useNavigate();

  //많은 정보들 => Array([])에 넣기
  const [Movies, setMovies] = useState([]);
  const [MainMovieImage, setMainMovieImage] = useState(null);
  const [CurrentPage, setCurrentPage] = useState(0);

  useEffect(() => {
    const endpoint = `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`;

    fetchMovies(endpoint);
  }, []);

  //바뀌는 endpoint 파라미터
  const fetchMovies = (endpoint) => {
    fetch(endpoint)
      .then((response) => response.json())
      .then((response) => {
        //...Movies : 원래 있던 Movies, ...response.results : 덮어 씌워짐
        setMovies([...Movies, ...response.results]); //Movies에 들어감
        setMainMovieImage(response.results[0]); //results의 첫 정보
        setCurrentPage(response.page);
        console.log(response.results);
      });
  };

  const loadMoreItems = () => {
    const endpoint = `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=${
      CurrentPage + 1
    }`;
    fetchMovies(endpoint);
  };

  return (
    <div style={{ width: "100%", margin: "0" }}>
      {/* Main Image movie이름 : backdrop_path*/}

      {MainMovieImage && (
        <MainImage
          image={`${IMAGE_BASE_URL}w1280${MainMovieImage.backdrop_path}`} //해당부분 이용
          title={MainMovieImage.original_title}
          text={MainMovieImage.overview}
        />
      )}
      <div style={{ width: "85%", margin: "1rem auto" }}>
        <h2>Movie by latest</h2>
        <hr />
        {/* Movie Grid Cards */}
        {/* gutter: 상하좌우 여백 생성 */}
        <Row gutter={[16, 16]}>
          {Movies &&
            Movies.map((movie, index) => (
              <React.Fragment key={index}>
                <GridCards
                  landingPage
                  image={
                    movie.poster_path
                      ? `${IMAGE_BASE_URL}w500${movie.poster_path}`
                      : null
                  }
                  movieId={movie.id}
                  movieName={movie.original_title}
                />
              </React.Fragment>
            ))}
        </Row>
      </div>

      <div style={{ display: "flex", justifyContent: "center" }}>
        <button onClick={loadMoreItems}>Load More</button>
      </div>
    </div>
  );
}

export default LandingPage;

 

 

2. MovieDetail에서 메인이미지 항목 만들기(LandingPage/Sections/MainImage.js)

 

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { API_URL, API_KEY, IMAGE_BASE_URL } from "../../../Config";
import MainImage from "../LadingPage/Sections/MainImage";
import MovieInfo from "./Section/MovieInfo";

function MovieDetail() {
  //useParams만 하면 object만 나옴
  const movieId = useParams().movieId;
  const [Movie, setMovie] = useState([]);

  useEffect(() => {
    let endpointInfo = `${API_URL}movie/${movieId}?api_key=${API_KEY}`;
    let endpoinCrew = `${API_URL}movie/${movieId}/credits?api_key=${API_KEY}`;

    fetch(endpointInfo)
      .then((response) => response.json())
      .then((response) => {
        // console.log(response);
        setMovie(response); //반드시 넣어야 상세페이지의 정보들이 들어옴
      });
  });

  return (
    <div>
      {/* header */}
      <MainImage
        image={`${IMAGE_BASE_URL}w1280${Movie.backdrop_path}`}
        title={Movie.original_title}
        text={Movie.overview}
      />
      {/* body */}
      <div style={{ width: "85%", margin: "1rem auto" }}>
        {/* Movie Info */}

        <br />
        {/* Actors Grid */}
        <div
          style={{ display: "flex", justifyContent: "center", margin: "2rem" }}
        >
          <button>Toggle Actor View</button>
        </div>
      </div>
    </div>
  );
}

export default MovieDetail;

 

* setMovie(response) 전

console.log(response) 정보

여기서 id가 useParams().movieId

 

 

3. MovieInfo에서 상세정보 항목 만들기(MovieDetail/Section/MovieInfo.js)

 

import React from "react";
import { Descriptions } from "antd";

function MovieInfo(props) {
  let { movie } = props;

  return (
    <Descriptions title="Movie Info" bordered>
      <Descriptions.Item label="Title">
        {movie.original_title}
      </Descriptions.Item>
      <Descriptions.Item label="release_date">
        {movie.release_date}
      </Descriptions.Item>
      <Descriptions.Item label="revenue">{movie.revenue}</Descriptions.Item>
      <Descriptions.Item label="runtime">{movie.runtime}</Descriptions.Item>
      <Descriptions.Item label="vote_average" span={2}>
        {movie.vote_average}
      </Descriptions.Item>
      <Descriptions.Item label="vote_count">
        {movie.vote_count}
      </Descriptions.Item>
      <Descriptions.Item label="status">{movie.status}</Descriptions.Item>
      <Descriptions.Item label="popularity">
        {movie.popularity}
      </Descriptions.Item>
    </Descriptions>
  );
}

export default MovieInfo;

 

 

4. MovieDetail로 MovieInfo 가져오기

 

MovieDetail.js

 

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { API_URL, API_KEY, IMAGE_BASE_URL } from "../../../Config";
import MainImage from "../LadingPage/Sections/MainImage";
import MovieInfo from "./Section/MovieInfo";

function MovieDetail() {
  //useParams만 하면 object만 나옴
  const movieId = useParams().movieId;
  const [Movie, setMovie] = useState([]);

  useEffect(() => {
    let endpointInfo = `${API_URL}movie/${movieId}?api_key=${API_KEY}`;
    let endpoinCrew = `${API_URL}movie/${movieId}/credits?api_key=${API_KEY}`;

    fetch(endpointInfo)
      .then((response) => response.json())
      .then((response) => {
        // console.log(response);
        setMovie(response);
      });
  });

  return (
    <div>
      {/* header */}
      <MainImage
        image={`${IMAGE_BASE_URL}w1280${Movie.backdrop_path}`}
        title={Movie.original_title}
        text={Movie.overview}
      />
      {/* body */}
      <div style={{ width: "85%", margin: "1rem auto" }}>
        {/* Movie Info */}
        <MovieInfo movie={Movie} />
        <br />
        {/* Actors Grid */}
        <div
          style={{ display: "flex", justifyContent: "center", margin: "2rem" }}
        >
          <button>Toggle Actor View</button>
        </div>
      </div>
    </div>
  );
}

export default MovieDetail;

 

 

5. 구글 크롬에서 확인하기