Class Components and State
react는 자동적으로 모든 class component의 render method를 실행하고자 한다.
state는 object이고 component의 data를 넣을 공간이 있다. (data는 변한다.) -> state에 바꾸고 싶은 data를 넣는다.
매번 state의 상태를 변경할 때 react가 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
#### 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 도메인이 나타나게 해준다.
package.json에 "homepage" : "https://{github유저명}.github.io/{project_name}"
package.json script에
"deploy" : "gh-pages -d build",
"predeploy" : "npm run build" 입력
deploy는 gh-pages를 호출하고 build폴더를 업로드한다.
build 폴더를 얻는 방법은 terminal에 npm run build 실행
deploy를 먼저 호출하면, predeploy가 자동적으로 실행되고 이름은 같아야 한다.
URL에 "https://{github유저명}.github.io/movie_app_2019" 입력하면 홈페이지 생성
<주의>
내용 수정 후 한 번더 업데이트(Deploy를 실행) 하기 위해 terminal에 npm run deploy 실행