2020. 6. 8. 14:28ㆍReactJS
지난 시간 배웠던 component life cycle에 대해서 다시 정리해보고, data를 fetch하는 법을 배워보자
이제 data를 fetch할 시간이다~
application을 mount(생겨나는 것, 태어나는 것, 살아 있는 것)하자마자 isLoading : true이다. javascript ternary oprator(삼항 연산자) 이건 react가 아니라 javaScript야.
import React from 'react';
class App extends React.Component{
state = {
isLoading: true
}
render(){
return <div>{this.state.isLoading ? "Loading" : "We are ready"}</div>
}
}
export default App;
isLoading이 true면 Loading이고, false면 we are ready
but this.state를 타이핑하고 싶지 않아서 새로운 JS의 ES6의 마법을 사용할 것이다.
render(){
const {isLoading} = this.state
return <div>{isLoading ? "Loading" : "We are ready"}</div>
}
퀴즈~ render를 하면 호출되는 life cycle method는 무엇일까?
정답은 componentDidmount
여기서 하려는 것은 setTimeout 이건 delay function이다.
timeout은 JS 꺼!
import React from 'react';
class App extends React.Component{
state = {
isLoading: true
}
componentDidMount(){
setTimeout(()=>{
this.setState({isLoading:false});
}, 6000);
}
render(){
const {isLoading} = this.state;
return <div>{isLoading ? "Loading" : "We are ready"}</div>;
}
}
export default App;
6초 뒤에 isLoading..이 we are ready로 바뀜!
이론적으로 우리가 한 일은 componentDidMount에서 data를 fetch한 것이다. 그리고 API로 부터 data fetching을 완료하면, "We are ready" 대신에 movie를 render하고 map을 만들고 movie를 render할 것이다.
import React from 'react';
class App extends React.Component{
state = {
isLoading: true,
movies : []
}
componentDidMount(){
setTimeout(()=>{
this.setState({isLoading:false, book: true});
}, 6000);
}
render(){
const {isLoading} = this.state;
return <div>{isLoading ? "Loading" : "We are ready"}</div>;
}
}
export default App;
니콜라스! 만약 내가 시작할 때 state에 뭔가 가지고 있는데, this.setState에 book: true처럼 뭔가 추가하면 에러가 생길까?
아니다. 너가 미래에 쓰고자하는 state를 선언하는 건 필수가 아니다. 따라서 보다시피 future state, 나는 단지 미래를 위해 계획한 것 뿐이다. 나는 movie state 안에 movie의 array를 가지고 있다.
내가 한 건 좋은 습관이다. 처음부터 여기에 선언할 필요는 없다. 이건 미래에 이쓸 수도 있는 것에 대한 것이다.
하지만 내가 말했듯이, 너의 state를 추가하는 것은 자유다. 너가 setState를 사용할 때 state 안에 default 값들을 선언할 필요는 없다.
'ReactJS' 카테고리의 다른 글
#4.1 Rendering the Movies (0) | 2020.06.10 |
---|---|
#4.0 Fetching Movies from API (0) | 2020.06.10 |
#3.2 Component Life Cycle (0) | 2020.06.08 |
#3.1 All you need to know about State (0) | 2020.06.08 |
#3.0 Class Components and State (0) | 2020.06.08 |