Web/React
[react] event handling & lifecycle ② - lifecycle
미니모아
2020. 4. 13. 00:49
반응형
-
Life Cycle ?
- 컴포넌트의 요람에서 무덤까지
component lifecycle - 컴포넌트가 계속 변화하기 때문에 중요
- 핵심 4가지
- Contructor
- State 구조 설정
- 컴포넌트가 Mount 하기 전에할 설정
- setState X
- CompopnentDidMount
- 필요한 데이터 요청
- 각종 비동기 요청 (Subsription)
- ComponentDidUpdate
- 업데이트 이후 수정할때
- If(){ setState() } //무한 반복 방지를 위해 조건문을 적용
- ComponentWillUnmount
- 데이터 요청, 비동기 함수, 타이머 종료
-> data leak 방지 - *setState X *
- 데이터 요청, 비동기 함수, 타이머 종료
- Contructor
-
console.log로 살펴보기
앞서 수정했던 App.js의 구조를 보면 다음과 같이 이루어져 있다.
자식 컴포넌트 :WorldClock
부모 컴포넌트 : App
각 컴포넌트의 lifecycle에 console.log를 찍어 확인해보자//자식 컴포넌트 class WorldClock extends React.Component{ constructor(props){ (코드 생략) console.log("Child) 시작합니다.") componentDidMount(){ console.log("Parent) 마운트 되었습니다.") } componentDidUpdate(){ console.log("Child) 업데이트!") } componentWillUnmount(){ console.log("Child) 언마운트!") } //부모 컴포넌트 class App extends React.Component { constructor(props){ (코드 생략) console.log("Parent) 시작합니다.") } componentDidMount(){ console.log("Parent) 마운트 되었습니다.") } componentDidUpdate(){ console.log("Parent) 업데이트!") } render(){ console.log("Parent) rendering") (코드 생략)
부모 constructor =>
부모 render =>
자식 constructor =>
자식 render=>
자식 Mount =>
부모 Mount =>
부모 Mount =>
순으로 진행 되는 것을 볼 수 있다. 이때 부모가 업데이트 되면 자식도 같이 업데이트가 되는데, 이를 방지 하기 위해서는ShouldComponentUpdate 혹은 PureComponent를 사용한다. 그러면 부모의 업데이트에 자식이 동기화 되지 않는다.
-
토글 버튼 만들기
토글 버튼을 만들어 timer를 사라지게 해보자. 이때 자식의 componentwillunmount에서 clearInterval 해주어야한다. 안 그러면 화면에서 사라져도 interval이 계속 돌아서 데이터 누수가 일어난다. 토글 버튼을 만들기 위해 event 생성 3단계를 거친다.//자식 컴포넌트 class WorldClock extends React.PureComponent{ componentDidMount(){ console.log("Child) 마운트 되었습니다.") //마운트 됐을때 interval이 동작하도록 함 this.timer = setInterval(()=>{ this.setState((state)=>( state.minute === 59? {hour: state.hour +1, minute : 0} : {minute:state.minute + 1} )) },5000) } (코드 생략) componentWillUnmount(){ console.log("Child) 언마운트!") // 이 클래스가 마운트 되지 않으면 interval를 제거하여 업데이트 되지 않게 한다. clearInterval(this.timer) } (코드 생략) //부모 컴포넌트 class App extends React.Component { constructor(props){ (코드 생략) this.state = { content: '', show:true // 1단계 : state 만들기 } //2단계 : handling function handlingClick = (e) =>{ //이전 상태의 show값을 토글해서 setState한다. this.setState((prevState)=>({show:!prevState.show})) } (코드 생략) render(){ (코드 생략) // 3단계 DOM에 handling function 적용 <button onClick={this.handlingClick}>손가락 튕기기</button> {this.state.show && // show값이 false면 아래 내용이 표시 되지 않음 this.cityTimeData.map((citytime,index)=> <WorldClock city={citytime[0]} time= {citytime[1]} key = {index}/> )} </div> ); } }
반응형