본문 바로가기
FrontEnd/React

React의 라이프사이클 , API 로딩처리

by oncerun 2020. 7. 12.
반응형

로딩 처리를 하기 위해 material-ui의 progress를 이용할 것입니다.

 

 

리액트 라이브러리는 다음과 같은 라이프사이클을 따릅니다.

 

1) constructor()

 

2) componentWillMount()

 

3) render()

 

4) componentDidMount()

 

 

props or state 가 변경되는 경우에는 => shouldComponentUpdate() 함수 등이 사용되어 다시 render()를 불러와서 view를 갱신하게 됩니다. 

리액트는 상태변화를 자동으로 검사해서 다시 그려주기에 편리합니다.

progress = () => {

const {completed} = this.state;
this.setState({ completed : completed >=  100 ? 0 : completed + 1 });

}

state = {

  customers:"",
  completed : 0 
}

state에 progress의 value값을 넣어줄 completed변수와 불릴 progress함수를 정의합니다.

 

이제 componentDidMount에 timer라는 함수를 지정해줍니다.

componentDidMount() {
  this.timer = setInterval(this.progress, 20);
  this.callApi()
  .then(res => this.setState({customers : res}))
  .catch(err => console.log(err))
}

componentWillUnmount() {

clearInterval(this.timer);

}


componentWillUnmount는 컴포넌트를 사용하지 않을 때 발생되는 이벤트 입니다.

 

 

다음과 같이 로딩 창을 보여줄 수 있습니다.

 

 

 

반응형

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

이벤트 처리  (0) 2020.07.13
MySQL DB 구축  (0) 2020.07.13
Window에서 리액트와 Node.js서버 실행시키기  (1) 2020.07.11
Node.js express  (0) 2020.07.10
material-ui  (0) 2020.07.10

댓글