728x90
반응형
Component Life Cycle
// 맨 처음에 실행
constructor(props) {
super(props);
console.log("hello");
};
// 랜더링시 실행
render(){
console.log("I'm rendering");
return (
<div>
<h1>The number is: {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
);
}
// 랜더링 완료 후 실행
componentDidMount() {
console.log("component rendered");
};
// 변경 후 랜더링 이후 실행
componentDidUpdate() {
console.log("I just updated");
};
// 페이지 이동이나 연결 종료시 실행
componentWillUnmount() {
console.log("Goodbye");
}
Component Life Cycle 예제
import React from 'react';
class App extends React.Component{
// component가 mount될 때, component가 screen에 표시될 때, component가 website에 갈 때 호출
constructor(props) {
super(props);
console.log("hello");
}
// state는 바꿀 데이터
state = {
count: 0
}
add = () => {
// state를 set할 때, react 외부의 상태에 의존하지 않는 좋은 방법(current 사용)
this.setState(current => ({ count: current.count + 1 }));
};
minus = () => {
this.setState(current => ({ count: current.count -1 }));
};
componentDidMount() {
console.log("component rendered");
};
componentDidUpdate() {
console.log("I just updated");
};
componentWillUnmount() {
console.log("Goodbye");
}
// setState를 호출할 때마다 react를 다시 render를 함!! (새로운 state로)
render(){
console.log("I'm rendering");
return (
<div>
<h1>The number is: {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
);
}
}
export default App;
반응형
'프로그래밍 > React' 카테고리의 다른 글
SPA(Single Page Application) (0) | 2021.03.02 |
---|---|
state 활용하기 (0) | 2021.02.23 |
component 예제 (0) | 2021.02.19 |
create-react-app 설치 (0) | 2021.02.17 |
TOAST UI Editor 설치하기 (0) | 2021.02.16 |