FRONT/REACT
[React] 노마드코더 영화 웹 서비스 만들기(1) - 사전 준비
연듀
2021. 8. 25. 16:23
사전 준비
import React from "react";
class App extends React.Component {
state = {
isLoading: true
};
render() {
const { isLoading } = this.state;
return <div>{isLoading ? "Loading..." : "Ready"}</div>
}
}
export default App;
mount(생겨나는 것) 되자마자 isLoading은 기본적으로 true 값을 갖는다.
삼항연산자를 사용해 isLoading이라면 "Loading" 텍스트를, 그렇지 않을 경우에는 "Ready"를 보여준다.
여기서 처음에 render()를 할 때 호출되는 life cycle 메서드는 componentDidMount()이다.
import React from "react";
class App extends React.Component {
state = {
isLoading: true,
};
componentDidMount() {
setTimeout(() => {
this.setState({ isLoading: false })
}, 5000);
}
render() {
const { isLoading } = this.state;
return <div>{isLoading ? "Loading..." : "Ready"}</div>;
}
}
export default App;
처음 마운트 될때 render()로 "Loading..."을 띄우고 componentDidMount에 자바스크립트의 setTimeout을 사용하여
5초 뒤에 isLoading 값을 false로 바꾼다.
"loading.." -> 5초 뒤에 "Ready" 로 바뀐다.
이제 우리가 해야할 일은 componentDidMount에서 data를 fetch하는 것이다.
그리고 API로부터 data fetching이 완료되면 "ready" 대신에 movie를 render하면 된다.
import React from "react";
class App extends React.Component {
state = {
isLoading: true,
movies: []
};
componentDidMount() {
setTimeout(() => {
this.setState({ isLoading: false })
}, 5000);
}
render() {
const { isLoading } = this.state;
return <div>{isLoading ? "Loading..." : "Ready"}</div>;
}
}
export default App;
state안에 movie array를 추가해놓자.
반응형