본문 바로가기

개발새발 개발자/ReactJS

[ReactJS] 6-1. Ajax in React

Ajax: Asynchronous Javascript and XM

XML보다는 JSON을 많이 쓰니 기억해두기.


JSON: Javascript Object Notation

오브젝트를 자바스크립트로 작성하는 기법.


1. Ajax 적용 전 사전 작업


Fetch 덕분에 쉽게 적용할 수 있다. 우리가 만든 fetch request는 url로 갈 것이다. fetch를 이용해서 get방식 사용하는 법을 배울 것이다. 사용할 url은 API - YTS 토렌트 영화 데이터베이스에서 가져올 것이다.


가져올 url

https://yts.am/api/v2/list_movies.json?sort_by=download_count


참고 parameters

https://yts.am/api#movie_details


sort_by로 정렬해서 데이터를 불러오기 위해 https://yts.am/api/v2/list_movies.json?sort_by=download_count?sort_by=rating 을 덧붙인다. 이 url이 최종적으로 리액트에서 불러오고 싶은 데이터다.


2. Ajax 적용하기


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
import React, { Component } from "react"
import "./App.css"
import Movie from "./Movie" //Movie.js에서 여기로 export한 컴포넌트를 import
 
class App extends Component {
  state = {}  // 삭제하면 'movies' property를 읽을 수 없음
 
  componentDidMount() {
    fetch("https://yts.am/api/v2/list_movies.json?sort_by=download_count?sort_by=rating")
  }
 
   _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>
    )
  }
}
 
export default App
cs

App.js에서 componentDidMount()에 있는 무비 리스트를 전부 지운다. 우리는 이제 url에 있는 진짜 DB를 가져올 것이기 때문이다. 지운 자리에 우리가 사전에 만들어놓은 url을 fetch와 함께 넣는다. 이때, state를 지우면 movies를 읽을 수 없으니 주의.


페이지에서 네트워크 탭으로 들어가면 bundle.js(리액트 파일) list_movies(DB, API)를 불렀다. 컴포넌트가 mount 되면 저 url을 fetch해오는 것이다. 이렇게 AJAX는 최신 자바스크립트 환경에서 비동기식으로 손쉽게 불러올 수 있다. AJAX를 쓰면 데이터를 불러올 때마다 페이지 새로고침을 하지 않아도 된다. 예를 들면 로딩할 때 API와 평점 등을 불러올 수 있다. 자바스크립트처럼 뒤에 숨어서!