ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [TIL] 2020-03-12
    Trainings/이전 TIL 기록 2020. 3. 12. 23:30

    [노마드 코더]

    ReactJS로 웹 서비스 만들기 #4. 2 Styling the Movies까지 수강

    [배운 내용]

    App.js

    import React from "react";

    import axios from "axios";

    import Movie from "./Movie";

    import "./App.css";

     

    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 });

        // 하나는 setState의 movies이고, 다른 하나는 axios에서 온 movies이다.

        // this.setState({moives:movies}); === this.setState({ movies });

        // 자바스크립트는 같은 항목이란 것을 이해한다.

      };

     

      componentDidMount() {

        this.getMovies();

      }

     

      render() {

        const { isLoading, movies } = this.state;

        // 자바스크립트 Ex6문법 -> this.state에서 isLoading, movies를 가져온 것.

        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}

                  />

                  // map()은 항상 뭔가로부터 return을 해야 한다.

                ))}

              </div>

            )}

          </section>

        );

      }

    }

    export default App;

    // componentDidMount()로 data를 fetch 할 것이다.

    // 그리고 API로부터 data fetching이 완료되면 "we are ready" 대신에 movie를 Render 하고 map을 만들고 moive를 render 하는 것이다.

    // 내가 state를 쓰는 건 자유! 굳이 state 안에 초기값을 선언할 필요는 없다.

    // 일반적으로 javascript에서 data를 fetch 하는 방법은 fetch를 사용하는 것이다.

    // 하지만 더 좋은 방법으로 Axios라고 부르는 것이 있다.

    // 우리는 axios로부터 온 data를 잡을 필요가 있다.

    // 왜냐하면 axios가 안에 있는 데이터를 우리에게 주기 때문이다.

    // 그렇기 때문에 우리는 그 데이터를 잡을 필요가 있다.

    // 그래야 state에서 사용할 수 있기 때문이다.

    // 잠시 기다려야 해 axios.get은 항상 빠르지 않다.

    // 우리는 javascript에게 componentDidMount 함수가 끝날 때까지 약간 시간이 걸릴 수 있다고 말해야 한다.

    // 그걸 위해 우리는 componentDidMount 앞에 async를 넣을 것이다.

    // async()는 비동기를 의미하고, "너는 이걸 기다려야 해"라는 말이다.

    // 함수 내부에서는 "내가 뭘 기다리길 원해"? axios?

    // axios가 끝날 때까지 기다렸다가 계속하라는 의미이다.

    // 즉, application은 render 하고, 처음에는 isLoading:true이며, application이 mount 된 후, 우리는 getMovies function을 호출한다.

    // getMovies는 axios.get을 사용해 하지만 axios.get은 완료되기까지 시간이 필요하기 때문에 await을 쓰게 되었다.

    // 만약 async를 사용하지 않는다면 await을 사용할 수 없다.

    // async await을 하는 것은 우리가 기본적으로 javascript에게 getMovies function에게 조금 시간이 필요하고 우리는 그걸 기다려야 한다는 것을 말하는 것이다.

    // Movies라는 array에 담긴 항목을 map() 함수를 이용해서 해당하는 항목을 꺼내서 Movie 컴포넌트를 가지고 적용

    // import "./App.css";를 함으로써, 각 태그의 class 이름을 해당 css 파일에서 쓸 수 있다.

     

    Movie.js

    import React from "react";

    import PropTypes from "prop-types";

    import "./Movie.css";

     

    function Movie({ year, title, summary, poster }) {

      return (

        <div class="movie">

          <img src={posteralt={titletitle={title/>

          <div class="movie__data">

            <h3 class="movie__title">{title}</h3>

            <h5 class="movie__year">{year}</h5>

            <p class="movie_summary">{summary}</p>

          </div>

        </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;

     

    // 이 경우에는 상상할 수 있다시피 movies component는 state를 필요로 하지 않는다.

    // 그래서 만약 component가 state가 필요 없을 경우 이게 class component가 될 필요는 없다.

    // 예를 들어 class App extends React.Component에서 React.Component를 필요로 하지 않는다.

    // 그래서 우리는 우리의 function component로 할 것이다.

    // 표지 이미지, title, id, summary, poster를 가져온다.

    // <div style={{backgroundColor:"red"}}></div> 자바스크립트의 스타일(CSS) 방식

     

    'Trainings > 이전 TIL 기록' 카테고리의 다른 글

    [TIL] 2020-03-14  (0) 2020.03.14
    [TIL] 2020-03-13  (0) 2020.03.13
    [TIL] 2020-03-09  (0) 2020.03.09
    [TIL] 2020-03-08  (0) 2020.03.08
    [TIL] 2020-03-07  (0) 2020.03.07

    댓글

Designed by Tistory.