관리 메뉴

막내의 막무가내 프로그래밍 & 일상

[React] 첫 리엑트 공부 정리 본문

웹/React

[React] 첫 리엑트 공부 정리

막무가내막내 2019. 9. 7. 18:42
728x90

 

리엑트를 처음 인강으로 공부하면서 간단하게 정리할려고합니다.

 

 

https://academy.nomadcoders.co/courses/enrolled/216871

 

ReactJS로 웹 서비스 만들기

ReactJS로 웹 서비스 만들기

academy.nomadcoders.co

강의는 노마드코더 니꼴라스 강사님꺼를 들었습니다.

 

 

prop type을 체크해줄 수 있다. (사용할려면 설치방법은 아래와 같다.)

npm i prop-types

prop의 type(String, number 등) ,  isRequired(꼭 있어야하는 값인지) , prop name을 체크해줄 수 있다.  

 

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

const foodILike = [
  {
    id: 1,
    name: "Kimchi",
    image:
      "http://aeriskitchen.com/wp-content/uploads/2008/09/kimchi_bokkeumbap_02-.jpg"
  },
  {
    id: 2,
    name: "Samgyeopsal",
    image:
      "https://3.bp.blogspot.com/-hKwIBxIVcQw/WfsewX3fhJI/AAAAAAAAALk/yHxnxFXcfx4ZKSfHS_RQNKjw3bAC03AnACLcBGAs/s400/DSC07624.jpg",
    rating: 4.9
  },
  {
    id: 3,
    name: "Bibimbap",
    image:
      "http://cdn-image.myrecipes.com/sites/default/files/styles/4_3_horizontal_-_1200x900/public/image/recipes/ck/12/03/bibimbop-ck-x.jpg?itok=RoXlp6Xb",
    rating: 4.8
  },
  {
    id: 4,
    name: "Doncasu",
    image:
      "https://s3-media3.fl.yelpcdn.com/bphoto/7F9eTTQ_yxaWIRytAu5feA/ls.jpg",
    rating: 5.5
  },
  {
    id: 5,
    name: "Kimbap",
    image:
      "http://cdn2.koreanbapsang.com/wp-content/uploads/2012/05/DSC_1238r-e1454170512295.jpg",
    rating: 4.7
  }
];

function Food({ name, picture, rating }) {
  return (
    <div>
      <h2>I like {name}</h2>
      <h4>{rating}/5.0</h4>
      <img src={picture} alt={name} />
    </div>
  );
}

Food.propTypes = {
  name: PropTypes.string.isRequired,
  picture: PropTypes.string.isRequired,
  rating: PropTypes.number
};

function App() {
  return (
    <div>
      {foodILike.map(dish => (
        <Food
          key={dish.id}
          name={dish.name}
          picture={dish.image}
          rating={dish.rating}
        />
      ))}
    </div>
  );
}

export default App;

예를들어 위와 같다면 name이라는 prop name를가지고 타입은 string 이고 꼭 있어야하는 값이라는 뜻이다. 또한 rating이라는 prop name을 갖고 number 즉 숫자형이 와야하지만 isRequired는 없으므로 꼭 있어야하는(전달받아야하는) 값은 아니다.

만약 이 규칙들에 벗어나면 에러가 발생한다.

추가로 자바스크립트에서 map은 배열을 하나씩 가져다 주는 역할을 한다.


 

여기서는 class component를 다룬다. 위에는 function component이다. class component는 React.Component를 상속받야아한다.

state는 object이고 component의 data를 넣을 공간이 있고 이 데이터는 변한다. 이게 state를 사용하는 이유이다.

setState는 새로운 state를 받아야한다. setState를 호출할때마다 react는 새로운 state와 함께 render 함수를 호출할것이다.

숫자값에 -1을 해주는 마이너스 버튼의 setState 사용을 예로들면,

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

export default App;

 

 


component 라이프사이클

 

import React from "react";

class App extends React.Component {
  state = {
    count: 0
  };
  add = () => {
    this.setState(current => ({ count: current.count + 1 }));
  };
  minus = () => {
    this.setState(current => ({ count: current.count - 1 }));
  };
  componentDidMount() {
    console.log("Component rendered");
  }
  componentDidUpdate() {
    console.log("I just updated");
  }
  componentWillUnmount() {
    console.log("Goodbye, cruel world");
  }
  render() {
    console.log("I'm rendering");
    return (
      <div>
        <h1>The number is: {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    );
  }
}

export default App;

MOUNTING

construcotr : component가 mount될 때, component가 스크린에 표시될때, component가 나의 웹사이트로 갈 때, construtor(생성자)를 호출한다.

static getDerviedStateFromProps() : 도 있지만 사용빈도가 적으므로 스킵

그 후 render를 호출한다.

componentDidMount()마지막으로 componentDidMount()를 호출하는데 이것은 이 component가 처음 render됐음을 알려준다.

 

UPDATING (ex 버튼같은 것을 눌러 state를 변경할때)

static getDerviedStateFromProps() : 위와동일

shouldComponentUpdate() : 기본적으로 업데이트를 할지말지 결정함

render() :

getSnapshotBeforeUpdate():

componentDidUpdate() : render()를 호출한 다음에 업데이트가 완료됬다고 말하면 이게 실행된다.

 

UNMOUNT( component가 죽을 때 )

componentWillUnmount()

 

 


fetch 대신 사용하는 axios 다운법 , 네트워크 요청 및 api 가져오는데 사용하는건 똑같

npm i axios

async await => ES6 문법

import React from "react";
import axios from "axios";

class App extends React.Component {
    state = {
        isLoading: true,
        movies: []
    };

    //async 비동기함수 , await 작업 끝날때까지 기다리게한다.
    //이렇게 안하면 자바스크립트는 이 함수를 기다리지않음.
    getMovies = async () => {
        const movies = await axios.get("https://yts-proxy.now.sh/list_movies.json");
    };
    componentDidMount() {
        this.getMovies();
    }
    render() {
        const { isLoading } = this.state;
        return <div>{isLoading ? "Loading..." : "We are ready"}</div>;
    }
}

export default App;

 


 

영화 api 이용해서 일단 타이틀만 띄워줌 , movie 모듈화

 

Movie.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;

 

App.js

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

class App extends React.Component {
    state = {
        isLoading: true,
        movies: []
    };

    //async 비동기함수 , await 작업 끝날때까지 기다리게한다.
    //이렇게 안하면 자바스크립트는 이 함수를 기다리지않음.
    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 (
            //처음 isLoading state는 true상태이므로 Loading... 이 뜨고 그후 componentDidMount()에서 getMovies()가 실행되고 바뀐 state로 render된다.
            <div>
                {isLoading
                    ? "Loading..."
                    : 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>
        );
    }
}

export default App;

 

 


 

 

 

728x90
Comments