Mi Lugarcito

React - LifeCycle 과 API 호출하기 본문

React & Next.js

React - LifeCycle 과 API 호출하기

selene park 2021. 3. 29. 11:28

React 컴포넌트 객체가 DOM 에 실제로 삽입되기 전까지의 과정은 아래와 같다. 이러한 과정을 마운팅 Mounting 이라고 부른다.

 

 

1) contructor() - 특정 컴포넌트 초기화

2) componentWillMount()

3) render() - 화면 그려준다

4)componentDidMount() - 처리가 끝난후에 불러와지는 함수 & 기본적으로 컴포넌트가 모두 구성된 직후인 componentDidMount() 함수에서 api 호출을 수행하면 효과적이다. 

 

 

데이터 변경

 

기본저그올 화면에 특정한 객체를 렌더링 하기 위해서는 props혹은 state를 사용해야 한다. props 와 state는 이러한 과정이 서로 다르지만 대략적으로 다음과 같은 순서로 수행된다.

 

1) shoudComponentUpgrade() : 기본적으로 컴포넌트의 데이터와 화면에 출력된 내용이 다를때 동작함, 기본적으로 true 값을 반환한다. 

2) componentWillUpdate() : 컴포넌트가 마운팅 해제될 때 수행. 컴포넌트의 동작을 위해 사용되었던 메소드들의 리소스 제거

3) render() : 화면구성 

4) componentDidUpdate() : 화면에 출력되는 화면 구성을 변경하고자 할때 사용. 이 함수에서 api 호출하기 때문에 많이 사용 

 

 

 

jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB As of Dec 2020, serving ~1.8 billion requests each month.

jsonplaceholder.typicode.com

 

HTML

<div id ="root"></div>

 

 

 

JS (render 함수가 수행된 이후에 ----> componentDidMount함수가 불러와 진다)

class ApiExample extends React.Component{
  constructor(props){
    super(props);
    this.state={
      data : ''
    }
  }
  
  //api 호출 클래스 
  callApi=()=>{
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then(res => res.json())
      .then(json=>{
        this.setState({
          data : json.title
        });
        
      });
  }
  
  componentDidMount(){
    //실제로 함수 불러와주기 및 활용하기 
    this.callApi();
  }
  
  render(){
    return(
      <h3> {this.state.data? this.state.data : '데이터를 불러오는 중입니다.'}</h3>
    );
  }
  
  
  
}


ReactDOM.render(<ApiExample/>, document.getElementById('root'));