티스토리 뷰

WEB/Reat

React 간단 정리

취뽀가자!! 2018. 12. 14. 15:41

Props

props는 메인 컴포넌트에서 서브컴포넌트에 정보를 줄 때 사용한다.

import React, { Component } from 'react';
import './App.css';
import Movie from './Movie';

const movies=[
{
title : "Iron Man",
poster : "http://pds21.egloos.com/pds/201805/15/21/f0041321_5afaeddcd6541.jpg"
},
{
title : "Iron Man",
poster : "http://image.cine21.com/resize/cine21/poster/2015/1124/18_18_34__56542b6a6febf[X230,330].jpg"
},
{
title : "spider man",
poster : "https://s-i.huffpost.com/gen/3910174/images/n-SPIDERMAN-628x314.jpg",
},
{
title : "Star Wars",
poster : "https://ph.sisain.co.kr/news/photo/201512/25098_49228_252.jpg"

}
]

class App extends Component {
render() {
return (
<div className="App">
{movies.map((movie, index)=>{
return <Movie title={movie.title} poster={movie.poster} key={index}/>
})}
</div>
);
}
}

export default App;

이렇게 메인에 정보를 다 때려박아둔다. 그리고 서브 컴포넌트에 정보를 보내주고 싶으면 <Movie title={movie.title}.../>와 같이 사용하면 줄 수 있다. 

map함수는 for문을 사용해 배열을 출력하는 것과 비슷한 원리이다. 그리고 map함수 인자 중에 index는 리액트에서 다수 개의 element를 가져올때 고유의 키를 부여하기 위함이다. 고유의 키가 없을 경우 에러 혹은 경고가 뜬다.

class Movie extends Component{
static propTypes ={
title : propTypes.string.isRequired,
poster : propTypes.string.isRequired
}
render(){
return(
<div>
{/* props로 App.js의 title을 가져옴 */}
<MoviePoster poster={this.props.poster}/>
<h1>{this.props.title}</h1>
</div>
)
}
}

위 코드는 서브 컴포넌트를 구현한 것이다. 메인에서 주는 정보를 받아서 출력하기 위해서는 this.props를 통해 받아 올 수 있다.


propTypes는 메인 컴포넌트에서 제공하는 정보의 타입을 결정하는 것이다. isRequired는 필수항목이기에 무조건 메인 컴포넌트에서 넘겨줘야 한다는 의미이다. 만약 메인에서 넘겨주지 않을 경우 에러가 뜨게 됩니다. propytpes를 사용하기 위해서는 import propTypes from 'prop-types'를 import해줘야 한다.


Component Lifecycle

컴포넌트는 여러 기능들을 정해진 순서대로 실행한다.

컴포넌트를 실행 할 때 아래와 같은 순서로 실행된다.

render : componentWillMount() -> render() -> componentDidMount()


위와 같은 사이클은 내가 원하든 안 원하든 자동으로 발생함.



업데이트는 좀 더 많은 것이 발생한다.


Updater : compoenetWillRecieveProps() -> shouldComponentUpdate() -> componentWillUpdate() -> render() -> componentDidUpdate()


첫 번째 단계에서는 컴포넌트가 새로운 props를 받았다는 것을 의미하고, 두 번째 단계에서는 만약 이전 props와 현재 props가 다르면  componentWillUpdate() == ture가 되어 실행되고, 같으면 false가 되어 실행되지 않는다.


세 번째 단계에서는 업데이트를 할 거라는 단계이다. 이 단계에서는 보통 로딩중이라는 창을 띄울 때 이 단계가 실행중이다. 이 단계가 끝나면 render()와 componentDidUpdate()가 되며 업데이트가 끝이 난다.


Change State

componentDidMount(){
setTimeout(()=>{
this.setState({
movies : [
...this.state.movies,
{
title:"Transformating",
poster : "https://upload.wikimedia.org/wikipedia/ko/thumb/e/e"+
"4/%ED%8A%B8%EB%9E%9C%EC%8A%A4%ED%8F%AC%EB%A8%B8_%EC%98%81%ED%99%94.jpg"+
"/250px-%ED%8A%B8%EB%9E%9C%EC%8A%A4%ED%8F%AC%EB%A8%B8_%EC%98%81%ED%99%94.jpg"
}
]
})
},1000)
}


컴포넌트의 state에는 this.state로 접근한다. 


setTimeout(()=>{},1000}은 1초뒤에 새로 갱신된다는 의미를 가진 함수이다.


state의 내용을 바꾸기 위해서는 this.setState를 사용하면 된다.  state의 내용을 바꾸게 되면 render()는 자동으로 업그레이드 될 것이다. 

그리고 State에 정의한 movies라는 리스트에 정보를 추가하고 싶다면 ...this.state.movies를 써 줘야 한다. 쓰지 않을 경우 movies 리스트는 새로 추가된 정보만 갖게 될 것이다.


참고로 state는 직접적으로 변경하면 안됨

this.state.greeting='something'



Loading states

우리가 필요한 데이터가 항상 즉시 존재하지는 않는다. 데이터 없이 컴포넌트가 로딩을 하고, 데이터를 위해 API를 불러서 API가 데이터를 주면 컴포넌트가 업데이트를 한다.
이럴 경우 필요한 것이 Loading states이다. Loading states는 아래와 같이 작성하면 된다.

_renderMovies=()=>{
const movies=this.state.movies.map((movie, index)=>{
return <Movie title={movie.title} poster={movie.poster} key={index}/>
})
return movies
}

render() {
return (
<div className="App">
{this.state.movies ? this._renderMovies : 'Loading'}
</div>
);
}
}

_renderMovies라는 함수를 정의하고 거기 안에 Movie컴포넌트를 리턴해 준다. 그리고 div사이에는 조건문을 넣어 state가 존재하면 _renderMovies를 리턴받고, 그렇지 않은 경우 Loading을 출력하도록 설계하는 것이 Loading states이다.


Smart vs Dumb Component

Smart component는 class로 설계한 컴포넌트를 말한다. 그리고 dumb 컴포넌트는 functional 컴포넌트를 의미한다.

class MoviePoster extends Component{
static propTypes ={
poster : propTypes.string.isRequired
}

render(){
return(
<img src={this.props.poster} alt="Movies Poster"/>
)
}
}

위와 같은 컴포넌트가 smart component이다. smart component는 render, component lifecycle, update, state가 필요하다.


아래와 같은 컴포넌트를 Dumb component 혹은 functional component라고 부른다.

function MoviePoster({poster}){
return(
<img src={poster} alt="Movies Poster"/>
)
}

이 컴포넌트는 render, component lifecycle, update, state가 필요없다. 단지, 한 개의 props만 존재하면 된다.


Dumb component의 propTypes는 아래와 같이 작성해 주면 된다.

MoviePoster.propTypes={
poster : propTypes.string.isRequired
}



AJAX

AJAX를 사용하면 새로고침을 하지 않아도 데이터가 바뀐 부부만 자동으로 업데이트되는 것을 말한다. 리액트에서 url을 AJAX로 불러오는 방법은 간단하다. fetch(url)을 사용하면 된다. 이렇게 하면 url이 바뀔 때 마다 url이 자동으로 업데이트 된다.

Promise

프로미스는 비동기식이기 때문에 첫 번째 기능과 두 번째 기능이 동시에 작업된다.
또 다른 기능은 시나리오를 잡는 방법을 만들어준다.
componentDidMount(){
fetch('https://yts.am/api/v2/list_movies.json?sort_by=like_count')
.then(resoponse => resoponse.json()) //then은 한 개의 attribute만 준다. 그리고 그 것은 object이다.
.then(json => console.log(json))
.catch(err=>console.log(err))
}

fetch를 사용해 url을 AJAX로 불러오고 then을 사용해 response를 json으로 바꿔준다. 그리고 catch를 사용해 에러가 났을 경우 콘솔로 알려주도록 한다.





'WEB > Reat' 카테고리의 다른 글

Block Update  (0) 2019.01.23
Middle Ware  (0) 2019.01.13
Redux(2)  (0) 2019.01.12
Redux(1)  (0) 2019.01.12
CRA(Create rReact App)  (0) 2019.01.08
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함