반응형
SMALL
App.js
import React, {Component} from 'react';
import MyComponent from './MyComponent'
class App extends Component{
state = {
counter:1,
error:false
}
// 실수로 잡지 못한 버그를 잡을 때
componentDidCatch(error,info){
this.setState({
error:true,
})
// API를 통해서 서버로 오류내용 날리기 가능
}
componentDidMount(){
console.log("componentDidMount");
}
handleClick=()=>{
this.setState({
counter: this.state.counter + 1
})
}
render(){
if(this.state.error){
return(
<div>에러가 났어요!</div>
)
}
return(
<div>
{this.state.counter<20 && <MyComponent value={this.state.counter}/>}
<button onClick={this.handleClick}>Click Me!</button>
</div>
)
}
}
export default App;
-> counter의 값이 20보다 작을 때만 MyComponent가 호출된다.
MyComponent.js
import React, {Component} from 'react';
class MyComponent extends Component {
state = {
value:0
}
constructor(props){
super(props);
console.log('constructor');
}
// 이 부분에서 props와 state 값이 같아진다.
// state.value가 props.value값을 따라가도록 설정.
static getDerivedStateFromProps(nextProps,prevState){
if(prevState.value!==nextProps.value){
return{
value : nextProps.value
}
}
return null;
}
shouldComponentUpdate(nextProps,nextState){
if(nextProps.value===10)return false; // 10 이면 false라서 렌더링 안된다.
return true;
}
componentDidUpdate(prevProps,prevState){
if(this.props.value!==prevProps.value){
console.log("value 값이 바뀌었다!",this.props.value);
}
}
// value 값이 20보다 커질 떄 실행된다.
componentWillUnmount(){
console.log('Good Bye');
}
render(){
return(
<div>
<p>props: {this.props.value}</p>
<p>state: {this.state.value}</p>
</div>
)
}
}
export default MyComponent;
-> 원래는 props: 1, state: 0 인데 getDerivedStateFromProps 함수를 통해 props와 state의 값이 같아진다.
반응형
LIST
'React' 카테고리의 다른 글
[study] 첫번째 수업 (0) | 2020.11.21 |
---|---|
[React] map 사용방법 (0) | 2020.10.30 |
[React] LifeCycle API 설명 (0) | 2020.10.04 |
[React] State 사용법 (0) | 2020.10.04 |
[React] 함수형 컴포넌트 (+비구조화 할당) (0) | 2020.10.04 |
댓글