ReactJS 20.09.15

Oh Joon·2020년 9월 15일
0

Class Components and State

  • class react component는 return을 가지지 않는다.
    function이 아니고 render method를 가지고 있기 때문이다.
    class component는 class이지만 react component로부터 확장되고 screen에 표시된다. 그걸 render method 안에 넣어야만 한다.

react는 자동적으로 모든 class component의 render method를 실행하고자 한다.

state는 object이고 component의 data를 넣을 공간이 있다. (data는 변한다.) -> state에 바꾸고 싶은 data를 넣는다.

매번 state의 상태를 변경할 때 react가 render function을 호출해서 바꿔주어야 한다.

  • setState
    setState 사용하지 않으면 새 state와 함께 render function이 호출되지 않는다. setState를 호출할 때 마다 react는 새로운 state와 함께 render function을 호출한다.
import React from 'react';
import PropTypes from "prop-types";


class App extends React.Component{
  state = {
    count : 0 
  };
  add = () => {
    this.setState(current => ({count: current.count + 1}));
  };
  minus = () => {
    this.setState(current => ({count: current.count -1}));
  };

  render(){
    return (<div>
      <h1>The number is : {this.state.count}</h1>
      <button onClick={this.add}>Add</button>
      <button onClick={this.minus}>Minus</button>
      </div>);
     // class이기 때문에 {count}가 아닌 {this.state.count}
  }
}


export default App;

Component Life Cycle

life cycle method는 기본적으로 react가 component를 생성하고 없애는 방법이다.

  • Mounting

    	1. constructor() [JS]
    
    	2. render()
    
    	3. componentDidMount()

    component가 mount되자 마자 호출된다.

  • Updating

    1. render()
    
    2. componentDidUpdate()

    setState를 호출하면, component를 호출하고, 먼저 render를 호출한 다음 업데이터가 완료되었다고 말하면 componentDidUpdate가 실행된다.

  • Unmounting(component가 죽을 때)

    1. componentWillUnmount

    component가 떠날 때 호출된다.


Fetching Movies from API

  • axios : fetch 위에 있는 작은 layer
    설치 : terminal -> npm i axios 실행
  • async / await
    axios.get은 항상 빠르지 않다. 그래서 JS에게 componentDidMount 함수가 끝날 때까지 약간 시간이 걸릴 수 있다고 전달해야 한다.(함수가 비동기라고 가르쳐줌)
#### 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}); // state와 axios 온 둘 다 불러옴 원래는 (movies:movies)
  };
  

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;
Movies.js
import React from "react";
import PropTypes from "prop-types";

function Movie({id, year, title, 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;

Deploying to Github Pages

gh-pages : 나의 웹사이트를 github의 github page 도메인이 나타나게 해준다.

  1. package.json에 "homepage" : "https://{github유저명}.github.io/{project_name}"

  2. package.json script에
    "deploy" : "gh-pages -d build",
    "predeploy" : "npm run build" 입력

    deploy는 gh-pages를 호출하고 build폴더를 업로드한다.

  3. build 폴더를 얻는 방법은 terminal에 npm run build 실행

    deploy를 먼저 호출하면, predeploy가 자동적으로 실행되고 이름은 같아야 한다.

  4. URL에 "https://{github유저명}.github.io/movie_app_2019" 입력하면 홈페이지 생성

<주의>
내용 수정 후 한 번더 업데이트(Deploy를 실행) 하기 위해 terminal에 npm run deploy 실행

profile
Front-end developer

0개의 댓글