스프링 프로젝트 (+react)

[ReactJS] 생성자 Constructor과 componentDidMount

junjunwon 2020. 10. 5. 18:03

출처 : firework-ham.tistory.com/29

 

[React] constructor() 생성자 사용법

class TempComponent extends Component{ constructor(props){ super(props); } render(){ return(<> ); } } React에서 Component를 생성할 때 state 값을 초기화하거나 메서드를 바인딩할 때 construcotr()를 사..

firework-ham.tistory.com

React에서 Component를 생성할때 state 값을 초기화하거나 메서드를 바인딩할때 constructor()를 사용한다.

해당 생성자 내에서는 어떤 API를 호출하는 것이 아니라, this.state로 초기값을 할당해줘야 한다.

생성자는 this.state를 직접 할당할 수 있는 곳으로 그 외에는 꼭 this.setState()를 사용해야한다.

 

생성자 내에서 구독 작업이나 외부 API 호출을 하면 안된다. -> 외부 API 호출이 필요하다면 componentDidMount()를 사용해야한다.

(기존 componentWillMount()는 곧 삭제될 예정으로 componentDidMount()로 수정해야 한다.