You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
prevProps, prevState, snapShot 세 개의 인자를 받으며 현재 상태는 this.props로 참조할 수 있다.
Unmount
컴포넌트가 Virtual DOM과 실제 DOM에서 사라질 때
componentWillUnmount
컴포넌트가 사라지기 직전에 호출
DOM에 달아놓은 이벤트리스너 제거
setTimeOut이나 setInterval을 해제해주는 작업을 해주는 경우가 많다.
Error
componentDidCatch
컴포넌트 내부에서 에러가 발생했을 때 호출된다.
실습
API로부터 정보 받아와서 렌더링
고양이 사진 및 정보를 API로 받아와서 class component로 렌더링하며 Life Cycle Method를 사용해보자
class 안에 componentDidMount 함수를 정의하되, API에서 fetch로 데이터를 받을 거니까 async 키워드를 함수 앞에 넣어준다.
classCatsextendsComponent{constructor(props){super(props)this.state={currentPage: 1,// API에서 받아올 페이지를 1로 초기화한다.breeds: []// API에서 받아올 데이터를 넣을 빈 배열}}asynccomponentDidMount(){console.log('start fetching')}}
fetch로 받은 고양이 정보를 response로 받고, json 형태로 바꾼 후 setState로 breeds에 넣어준다.
page 버튼 만들기
버튼 누르면 다음 페이지의 정보를 받아오게끔 constructor state에 1로 초기화했던 currentPage를 바꿔가며 호출한다.
현재 렌더링하고 있는 태그가 ul인데, 렌더함수는 하나의 태그만 리턴할 수 있으므로 div로 씌운 후 ul 위에 onclick 속성을 준 버튼태그를 마크업해준다.
render(){return(<div><buttononclick=()=>{this.setState((prevState)=>{return{currentPage : prevState.currentPage-1}})}> 이전 페이지 </button><buttononclick=()=>{this.setState((prevState)=>{return{currentPage : prevState.currentPage+1}})}> 다음 페이지 </button></div>)}
render 함수 상단에 다음 페이지에서 데이터를 가져올 componentDidUpdate 함수를 작성한다.
fetch로 가져올 거니까 async와 await 사용해주기
render(){asynccomponentDidUpdate(prevProps,prevState){if(prevState.currentPage===this.state.currentPage){return// 변화가 없다면 그냥 넘어간다.}constresponse=awaitfetch('https://api.thecatapi.com/v1/breeds?page=${prevState.currentPage}&limit=3',{headers: {'x-api-key': apiKey}})constbreeds=awaitresponse.json()this.setState({breeds: prevState.breeds.concat(breeds),})}
utils로 반복되는 함수 빼주기
fetch로 가져오는 것이 반복되니까, utils 폴더 속 api.js 파일을 생성하여 빼준다.
page를 매개변수로 받고 인자로 들어오는 값이 number인지 validate해준다.
constapiKey='{API KEY값}'exportconstgetCatBreeds=async(currentPage)=>{if(typeofcurrentPage!=='number'){thrownewError('getCatBreeds 함수의 currentPage 파라미터는 Number이어야 합니다.')}constresponse=awaitfetch('https://api.thecatapi.com/v1/breeds?page=${currentPage}&limit=3',{headers: {'x-api-key': apiKey}})constbreeds=awaitresponse.json()returnbreeds}
component 파일로 돌아와 import해준다.
import{getCatBreeds}from'../utils/api'
Loading Indicator 만들기
첫 렌더링과 update하는 함수에서 Fetch 가 완료되어 렌더링할 때까지 loading indicator를 띄워준다.
사용성에 따라 방법과 위치는 달라질 수 있지만, 우리는 버튼 태그 뒤에 넣어주는 것으로 하자.
constructor에서 state에 isLoading 변수를 false로 초기화해준다.
componentDidMount 함수의 처음, componentDidUpdate 함수의 처음에 setState로 isLoading값을 true로 변경해준다.
API로 데이터를 받아와 breeds를 state에 넣어줄 때 isLoading도 false로 값 변경해준다.