상세 컨텐츠

본문 제목

recast.ly - React

Programming/React

by 쌩우 2019. 6. 14. 20:32

본문

recast.ly는 Youtube API를 이용하여 실제 youtube처럼 검색 및 동영상 시청이 가능하도록 만드는 sprint이다.
실제로 끝마치고 되돌아보니, react를 사용한 첫 sprint로 도전하기에 아주 제격이라는 생각이 들었다.

sprint를 진행하기에 앞서, react의 핵심 개념을 짚고 넘어가야만 한다.

  1. stateless functional component & stateful classical component의 차이
  2. props flow & state
  3. life cycle & life cycle method

Component

stateful classical component를 사용하는 경우는 명료하다.

  • 어떤 state를 지정해서 관리하는 경우
  • life cycle method(componentDidMount, render 등)
  • state를 선언하여 props로 하위 컴포넌트에 전달하고자 하는 경우

setState

: 하위 컴포넌트에서 상위 컴포넌트의 state를 변경하려면, 직접적으로는 접근할 수 없다.
바꾸고자 하는 state가 있는 컴포넌트에서부터 setState 함수에 this binding을 시킨 뒤,
하위 컴포넌트까지 props에 함수를 담아 내려주어야 한다.
실제 실행되는 시점은 하위 컴포넌트 컨텍스트이지만, 이미 binding 되어있는 this가 state가 있는 컨텍스트이기 때문에 해당 부분의 state가 바뀔 수 있게 된다.

fetch와 같은 비동기적 작업

: Youtube API를 적용하여, 서버로부터 정보를 불러오고자 할 때 fetch를 사용하였다.
하지만 실제로 응답받은 정보를 받아서 하위컴포넌트로 넘겨주어야 하는 부분은 최상위 컴포넌트인 App.js 부분이었다. 응답받은 정보를 어떻게 App의 컨텍스트로 받아올 수 있을까?
답은 fetch API에서 json 정보를 받은 시점에서 callback을 실행해주는 것이다.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.currentVideo = this.currentVideo.bind(this);
    this.state = {
      videos: false,
      currentVideo: false,
      myWord: (q) => {
                      searchYouTube(q, YOUTUBE_API_KEY, (json)=>{
                        this.setState( {
                          videos: json.items,
                          currentVideo: json.items[0]
                        } )
                      })
                    }
    }
  }
  //가장 처음 constructing 된 후, 가짜 데이터로 render가 일어난 후에 componentDidMount 부분이 실행되면서
  //실제 사용하고자 하는 Youtube API의 정보를 불러온다.
componentDidMount() {
    //console.log('MOUNT!!', this);
    searchYouTube('codestates', YOUTUBE_API_KEY, (json)=>{
      this.setState( {
        videos: json.items,
        currentVideo: json.items[0]
        } )
    });

**search 부분, debounce 부분 내용 추가하기

'Programming > React' 카테고리의 다른 글

Redux - State Container  (0) 2019.07.03
React app 개발 시의 고려 사항  (0) 2019.06.18
checkpoints in react  (0) 2019.06.14
Components and Props - React  (0) 2019.06.11
Rendering Elements - React  (0) 2019.06.11

관련글 더보기

댓글 영역