<복습>
https://wook-2124.tistory.com/134
[React] #3.2 Component Life Cycle (#코딩공부)
https://youtu.be/ycOQk7SZWkM <복습> https://wook-2124.tistory.com/133 [React] #3.1 All you need to know about State (#코딩공부) https://youtu.be/38I5K3p42WU <복습> https://wook-2124.tistory.com/132..
wook-2124.tistory.com
<준비물>
https://code.visualstudio.com/
Visual Studio Code - Code Editing. Redefined
Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications. Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.
code.visualstudio.com
1. 삼항 연산자(조건 연산자, Ternary Operator)

이제 Movie App으로 이어질 Movie Component를 만들어보자.
먼저 component가 mount(생성)되면 state(상태)는 isLoading: true인 로딩중인 상태일 것이다. 다음으로 render function에 const로 isLoading을 this.state로 정의해주고, return으로 삼항 연산자(조건 연산자, Ternary Operator)를 사용해서 isLoading을 반환했다.
삼항 연산자를 해석하자면, isLoading ?(if) (isLoading == true면) "Loading..."을 반환하고 :(else, 그렇지 않고 false면) "We are ready"를 반환하는 JavaScript이다.

원래 condition(조건)으로 { this.state.isLoading }을 써줘야하는데 새로운 JavaScript Version인 ES6를 이용해서, const로 isLoading를 { this.state }라고 해서 isLoading 자체를 바로 사용할 수 있게됐다.

localhost를 가면 state의 isLoading이 아직 true인 상태이기 때문에 "Loading..."이 return됐다.
2. setTimeout

componentDidMount로 render function보다 먼저 호출되는 Life Cycle Method을 이용해보자. 사진 설명에 적힌 것처럼 component가 mount(생성)되자마자 호출되서 render function보다 먼저 실행된다.

setTimeout은 React 것이 아니라 JavaScript 것이다. setTimeout은 시간 지연함수(delay function)로써 일정시간이 지난 뒤 함수를 실행시키는 함수이다.
( ) =>로 function()을 간소화 시키고, { this.setState({ isLoading: false }) }, 6000으로 state인 isLoading을 setState를 이용해서 ture에서 false로 6초 뒤 바꿔주는 함수를 적었다.
isLoading이 false로 바뀌고 나면 "Loading..."에서 "We are ready"가 return될 것이다.

componentDidMount에서 설정한 setTimeout으로 6초 뒤에 setState로 인해 isLoading state가 false로 바뀌고, 그 다음 render function에서 다시 isLoading state가 false로 인식됨으로써 "We are ready" 문구가 출력된다.
[JavaScript] 시간 지연 함수, 일정 시간 뒤 실행시키기, setTimeout() {}
자바스크립트 함수중에서 자주 사용되는 타이머 함수가 있습니다. 바로 setTimeout()이죠! 아래는 어떻게 동작하고 사용하는지 자세히 알아보고자 합니다.
webisfree.com
3. What's next?

앞으로 할 일은 componentDidMount에서 API data를 fetch(가져)오는 것이다. API로부터 data feching이 완료되면 "We are ready"문구 대신 movie를 다시 render(표현)하고 map을 만들어 각각의 movie를 render해줄 것이다.

state로 movies [ ]를 미리 만들어 두는 것처럼, future state를 설정하는 것은 좋은 습관이다. 처음부터 미리 선언할 필요는 없지만, 미래에 있을 수도 있는 것에 대해 미리 계획을 해두는 것이다.
'JavaScript > React' 카테고리의 다른 글
[React] #4.1 Rendering the Movies (#코딩공부) (0) | 2020.06.08 |
---|---|
[React] #4.0 Fetching Movies from API (#코딩공부) (0) | 2020.06.02 |
[React] #3.2 Component Life Cycle (#코딩공부) (0) | 2020.05.27 |
[React] #3.1 All you need to know about State (#코딩공부) (0) | 2020.05.26 |
[React] #3.0 Class Components and State (#코딩공부) (0) | 2020.05.23 |
댓글