Constructor
브라우져 나타나기전에 호출 컴포넌트가 생성될때 이 함수 가 호출됨
componentDidMount
외부 라이브러리 연동 데이터 요청(ajax ) dom에 관한 작업 스크롤이나 크기 읽어오기 등등
이러한 이벤트들도 가능
Static getDervedStateFromProps()
Props가 받아온값을 state로 동기화 시켜주는 작업에 사용
Props가 바뀔때마다 state값을 리턴해주면된다.
class MyComponent extends Component {
state = {
value : 0
}
static getDerivedStateFromProps(nextProps , prevState){
if(prevState.value !== nextProps.value){
return {
value : nextProps.value
}
}
return null
}
class App extends Component {
state = {
counter : 1 ,
}
constructor(props) {
super(props);
console.log('constructor');
}
componentDidMount() {
console.log('didMount');
}
handelClick = () => {
this.setState({
counter : this.state.counter +1
});
}
render() {
return (
<div>
<MyComponent value={this.state.counter} />
<button onClick={this.handelClick}>click me</button>
</div>
);
}
}
버튼 누를때마다 1씩 증가되는 counter 그 값이 value가 되고
해당 vlaue는 Mycomponent에 props가 되고 그 props에 state가 동기화 된것이다.
shouldComponentUpdate
Return false하면 업데이트 안함
Return true 하면 업데이트 함.
Virtual dom에 랜더링이 필요없는경우 꺼두면 성능적으로 도움됨.
shouldComponentUpdate(nextProps, nextState){
if(nextProps.value === 10 ) return false;
return true;
}
이런식으로 넣으면 10에서는 렌덩링을 하지않아 표현되지않는다.
getSnapshotbeforeUpdate
DOM 업에이트 일어나는 시점마다 스냅샷을 남김
componentDidupdate
Render 호출된 다음에 발생하게 되는 이벤트
componentDidUpdate(prevProps, prevState) {
if (this.props.value !== prevProps.value) {
console.log('value 값이 바뀌었다!', this.props.value);
}
}
componentWillUnmount
컴포넌트가 필요없을시에 제거
componentWillUnmount() {
console.log('Good Bye');
}
<div>
{this.state.counter < 10 && <MyComponent value={this.state.counter} />}
<button onClick={this.handelClick}>click me</button>
</div>
10이 넘으면 goodbye가 나옴
componentDidCatch
에러가 발생하면 이것이 실행된다.
부모에서 사용하면된다.