1
2
3
4
5
6
7
constructor(props){
super(props);
console.log('constructor')
console.log(props) // {name: "sw"}
this.state = { count: 0, name : '[κΈ°λ³Έ nameκ°]' };
}
1
2
3
4
5
6
7
8
9
10
11
12
static getDerivedStateFromProps(props, state) {
console.log("getDerivedStateFromProps");
console.log(props, state); // {name: "sw"}, {count: 0, name: "[κΈ°λ³Έ nameκ°]"}
if(props.name !== state.name){
return { name: props.name }; // (*)
}
return null; // μ무 μΌλ μΌμ΄λμ§ μμ
}
// (*) λ€μμ μ€νλλ render λ©μλμμ κ°μ΄ λ³κ²½λ κ²μ νμΈν μ μλ€.
// {name: "sw"}, {count: 0, name: "sw"}
1
2
3
4
5
6
7
8
render(){
console.log("render");
console.log(this.props, this.state) // {name: "sw"}, {count: 0, name: "sw"}
return(
<div>μλ
?</div>
)
}
1
2
3
componentDidMount(){
console.log("componentDidMount");
}
1
2
3
4
5
6
shouldComponentUpdate(nextProps, nextState){
console.log("shouldComponentUpdate");
console.log(nextProps, nextState); // countλ₯Ό +1 ν κ²½μ° => {name: "sw"}, {count: 1, name: "sw"}
return nextState.count <= 10; // count κ°μ΄ 10 μ΄νμΈ κ²½μ°μλ§ render(), componentDidUpdate() μ΄ μ€νλ¨
}
componentDidUpdate()
μ 3λ²μ§Έ μΈμλ‘ μ λ¬λλ€.1
2
3
4
5
6
7
8
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log("getSnapshotBeforeUpdate");
if(prevState.count >= 5){ // count κ°μ΄ 6 μ΄μμ΄ λλ©΄ 'μ€λ
μ·!' μ λ°ννλ€.
return "μ€λ
μ·!";
}
return null;
}
getSnapshotBeforeUpdate()
μμ return λ κ°μ λ°λλ€.1
2
3
4
5
6
7
componentDidUpdate(prevProps, prevState, snapshot) {
console.log("componentDidUpdate");
console.log(prevProps, prevState, snapshot);
// count κ°μ΄ 5 μ΄νμΈ κ²½μ° => {name: "sw"}, {count: 0~4, name: "sw"}, undefined
// count κ°μ΄ 6 μ΄μμΈ κ²½μ° => {name: "sw"}, {count: 5~n, name: "sw"}, "μ€λ
μ·!"
}
1
2
3
componentWillUnmount() {
console.log("componentWillUnmount");
}
1
2
3
4
5
6
static getDerivedStateFromError(error) {
console.log("componentWillUnmount");
console.error(error);
return { hasError: true };
}
1
2
3
4
5
6
componentDidCatch(error, info) {
console.error("componentDidCatch");
console.log('error',error)
console.log('info',info)
}
https://ko.reactjs.org/docs/react-component.html
https://react.vlpt.us/basic/25-lifecycle.html