배고픈 개발자 이야기

1.React 기본 응용 웹사이트 만들어 보기 본문

언어/React

1.React 기본 응용 웹사이트 만들어 보기

이융희 2019. 9. 8. 11:25
728x90

https://github.com/yoonghee/reactStudy

 

yoonghee/reactStudy

React JS Fundamentals Course (2019 Update!). Contribute to yoonghee/reactStudy development by creating an account on GitHub.

github.com

 

완성된 페이지

노마드 React 인강 따라해보기

 

index.html root에 react는 밀어 넣는거임

react를 빠르게 하는 이유

react는 소스코드에 처음부터 HTML을 넣지 않고,

HTML에서 HTML을 추가하거나 제거하는 법을 알고있어

그래서 application이 로드할때 빈 HTML을 로드하게 되고

그런 다음에 react가 HTML을 밀어넣게돼 너의 component에

작성해뒀던 것들말야

virtual이고 존재하지 않기 때문이지

virtual DOM의 개념 - react가 만들어 내는것

 

모든것은 component임 component가 data를 보여주게 할거야

component는 html을 반환하는 함수임

 

<App /> javascript와 html사이의 개념 JSX라고 부름 react가 소개한 유일한 개념

나머지 개념은 javascript

 

react application이 하나의 component만을 rendering 해야함

jsx는 javascript + HTML이야. Component를 만들고 어떻게 사용하는지에 대한 것이야 알겠지?

 

JSX의 두번째 파트 - 컴포넌트에 정보를 보낼 수 있다는것

react가 멋진 이유는 재사용 가능한 component를 만들 수 있다는 점

component를 계속해서 반복해서 사용할 수 있는것

 

<Food name="kimchi" /> - food component에 kimchi라는 value로

prop name을 줬어 알겠지?

prop은 배열이나 boolean등 다양하게 다양한 이름으로 정의가 가능

Food - component는 대문자로 시작해야하고

부모 컴포넌트의 props는 자식 컴포넌트의 argument로 감

 

웹사이트에 동적데이터를 추가하는 방법

API로 데이터를 가져왔다고 가정합니다.

food array를 array로 가져오고 자동적으로 내가 좋아하는 food를 이름과 함께 어떻게 렌더링하지? - javascript함수 이용(map) : react가 javascript인 이유

map이 하는일은 렌더링 - array로 부터 array를 줌

map은 array의 각 item에서 function을 실행하는 array를 가지는 javascript function이며 그 function의 result를 갖는 array를 너에게 줘

map은 function을 취해서 그 function을 array의 각 item에 적용해

friends.map(current => { console.log(current); return 0 })

friends.map(function(friend){ return friend + " ❤"; })

 

 

component life sycle

state는 보통 우리가 동적 데이터와 함께 작업할 때 만들어져, 변하는 데이터, 존재하지 않는 데이터

setstate - rendering refresh (update)

mounting - component가 생성되는것

construct() - component가 웹사이트로 갈 때 호출됨

componentdidmount - redering된 이후 호출됨

updating

componentdidupdate - rendering된 이후 호출됨

unmounting - component가 죽는것 (state, page바뀔 때)



getMovies = async() => {

const movies = await axios.get("https://yts-proxy.now.sh/list_movie.json");

}

componentDidMount () {

this.getMovies();

}

이 함수가 비동기라고 한거야. 이 말은 "너는 이걸 기다려야 해"라는 말이야

async + await은 axios.get이 끝나길 기다렸다가 계속 진행함, 을 하지 않으면 javascript는 코드를 기다려주지 않음, 더 많은 다른 코드가 필요하게 됨

-es6는 ECMA script의 새로운 버전

 

App.js

import React from 'react';
import PropTypes from 'prop-types';
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 }) // movies get : movies와 같이 동작함
  } // 4.1 3:23
  componentDidMount () {
    this.getMovies();
  }

  render() {
    const { isLoading, movies } = this.state; // ES6문법
    return (
        <section className="container">
            {isLoading ? (
                <div className="loader">
                       <span className="loader__text">Loading...</span>
                </div>
        ) : ( 
         <div className="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}
                genres={movie.genres}
              />
            ))}
          </div>
        )}
      </section>
    )
  }
}

export default App;

 

 

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(, document.getElementById('potato'));


Movie.js

import React from "react";
import PropTypes from "prop-types";
import "./Movie.css"

function Movie({id, year, title, summary, poster, genres}){
    return (
        <div className="movie">
            <img src={poster} alt={title} title={title} />
            <div className="movie__data">
                <h3 className="movie__title">{title}</h3>
                <h5 className="movie__year">{year}</h5>
                <ul className="movie__genres">
                    {genres.map((genre, index) => (
                        <li key={index} className="genres__genre">{genre}</li>
                    ))}
                </ul>                
                <p className="movie__summary">{summary.slice(0, 180)}...</p>
            </div>
        </div>
    );
}

Movie.prototypes = {
    id: PropTypes.number.isRequired,
    year: PropTypes.number.isRequired,
    title: PropTypes.string.isRequired,
    summary: PropTypes.string.isRequired,
    poster: PropTypes.string.isRequired,
    genres: PropTypes.arrayOf(PropTypes.string).isRequired
}

export default Movie;

 

'언어 > React' 카테고리의 다른 글

0.React 기본개념  (0) 2019.09.08
Comments