componentDidMount()

d·2020년 7월 19일
0

componentDidMount

값을 호출해서 state에 저장하면 계속해서 render가 또 작동된다.
따라서, componentDidMount가 필요하다.

"최초에 한번만 하면 된다."를 작동하려면
componentDidMount()를 쓰면 된다.

componentDidMount() {

}

이 안에 fetch 작성했던 것을 그대로 복사해서 넣어보면 된다.

  1. fetch("http://jsonplaceholder.typicode.com/users")
    .then(abc => abc.json())
    .then(res => console.log(res));
    }

위 fetch 작성했던 것을 복사해서 그대로 붙여넣은 결과는 다음과 같다.

componentDidMount() {
	fetch("http://jsonplaceholder.typicode.com/users")
	.then(abc => abc.json())
    .then(res => console.log(res));
    }
}

왜 render 후에 fetch를 하는가?

일종의 약속인데 그림을 참고해보자 출처 : wecode영상

constructor가 생성자 함수다.
그래서, 생성해야하는 모든 조건을 이 함수를 작성함으로써 설계가 된다.

이 후, render()를 하기 전에
state를 작성하게 되고 componentDidMount로 같은 값이 반복되지 않도록 하는데,
1. constructor(){
}
2. componentDidMount() {
}
3. render() {
}
순으로 적게 되면, "이 곳에서 데이터 로딩을 처리하자"
협업하는 사람들끼리 장소를 지정해준 약속 같은 것.

Mount란?

"이 화면이 보여지고 있다. 이 component가 보여지고 있다" 라는 뜻

"render함수가 돌아서 jsx가 리턴되는데,
이 행위 자체를 Mount되었다" 라고 한다.

render가 필요한 이유

화면 밑에 있는
return

<div className="Monsters">

같은 jsx를 리턴하기 위해서 render가 필요하다.

DidMount가 render후에 불리는데,

여담 "서버를 켠다"

npm start한다는 뜻.

profile
d

0개의 댓글