
class Change extends React.Component{
constructor(props){
super(props)
this.state = {
color: 'red'
}
}
changeColor = () =>{
this.setState({color:' blue'})
}
render(){
return(
<div>
<h1>It is a {this.state.color}</h1>
<button onClick={this.changeColor}>Change Color</button>
</div>
)
}
}
클래스 컴포넌트에 적용되는 생명주기 (Life Cycle)에 대해 알아보자.
생명주기란 앱이 실행되고 종료되는 과정을 특정 시점 별로 나눠둔 것을 의미한다.
파이썬의 클래스 객체로 예를 들면, 클래스가 생성되면 생성자가 호출되고 소멸되면 소멸자가 호출된다.
간단하지만 이러한 요소의 시작과 끝이 바로 생명주기다.
React의 생명주기는 컴포넌트가 이벤트를 다룰 수 있는 시점을 말하며 마운트, 업데이트, 언마운트 상태로 구성되어 있다. 컴포넌트가 실제 DOM에 삽입되는 것을 마운트, 컴포넌트가 변하는 것을 업데이트, 컴포넌트가 DOM 상에서 제거 되는 것을 언마운트라고 한다. 특정 시점별 호출되는 생명주기 메소드에 대해 알아보자.

React의 생명주기 메소드는 다음과 같은 것들이 있다.
constructor() : State 데이터를 초기화 하는 메소드
render() : 클래스 컴포넌트에서 반드시 구현되어야 하는 메소드
componentDidMount() : 컴포넌트가 마운트 된 직후 호출되는 메소드
componentDidUpdate() : 업데이트가 진행된 직후 호출되는 메소드
componentWillUnmount() : 컴포넌트가 마운트 해제되어 제거되기 직전에 호출되는 메소드
class Header extends React.Component{
constructor(props){
super(props)
this.state = {favoriteColor: "red"}
}
componentDidMount(){
setTimeout(() => {
this.setState({favoriteColor: "yellow"})
})
}
render(){
return (
<h1>My Favorite Color is {this.state.favoriteColor}</h1>
)
}
}
ReactDOM.redner(<Header/>, document.getElementById('root'))
만약 동적인 앱을 만들고 싶다면 이러한 생명주기에 대해 잘 알아야 한다. 예를 들어 사용자가 특정 행동을 완료할 때마다 알림을 주고 싶다면 컴포넌트가 마운트 된 이후 호출되는 componentDidMount() 메소드를 이용해 알림을 줄 수 있다. 즉 원하는 시점에 따라 컴포넌트가 다른 동작을 실행하길 원한다면, 생명주기 메소드에 대해 알고 있어야 함!
import React from 'react'
class App extends React.Component{
constructor(props){
super(props)
this.state = {
name: 'effy',
job: 'developer',
}
}
// name 데이터를 변경하는 메소드
onNameHandler = event => {
// setState를 사용해 name 데이터 업데이트 기능을 구현
this.setState({
name: event.target.value,
})
}
// job 데이터를 변경하는 메소드
onJobHandler = event => {
// setState를 사용해 job 데이터 업데이트 기능을 구현
this.setState({
job: event.target.value
})
}
onClickHandler = () => {
alert(`이름: ${this.state.name}, 직업: ${this.state.job}`)
}
render(){
const {name, job} = this.state;
return(
<div>
<div>name: <input type="text" value={name} onChange={this.onNameHandler}/></div>
<div>job: <input type="text" value={job} onChange={this.onJobHandler}/></div>
<button type="button" onClick={this.onClickEventHandler}></button>
</div>
)
}
}
export default App;
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App/>, document.getElementById('root'))