var isLoaded=false;
var LifeCycle = React.createClass({
getInitialState(){
$('#output').append("getInitialState\n");
return{
childFoobar: false
};
},
getDefaultProps(props){
console.log(this.props,props);
$('#output').append("[로딩될 때]\n\n");
$('#output').append("getDefaultProps\n");
return{}
},
componentWillReceiveProps(nextProps){
console.log('componentWillReceiveProps is called');
$('#output').append("componentWillReceiveProps\n");
if(nextProps.childFoobar){
this.setState({
childFoobar: nextProps.childFoobar
});
}
},
componentWillMount(){
$('#output').append("componentWillMount\n");
},
componentDidMount(){
$('#output').append("componentDidMount\n");
},
shouldComponentUpdate(){
$('#output').append("shouldComponentUpdate\n");
//return true;
},
componentWillUpdate(){
$('#output').append("componentWillUpdate\n");
},
componentDidUpdate(){
$('#output').append("componentDidUpdate\n");
},
componentWillUnmount(){
$('#output').append("componentWillUnmount\n");
},
changeState(){
$('#output').append("\n[state가 바뀔 때]\n\n");
this.setState({
childFoobar :true
});
},
render(){
$('#output').append("render\n");
return(
<div className="lifecycle">
<a href="#" onClick={this.changeState}>state가 바뀔때(클릭)</a>
</div>
);
}
});
var LifeCycleParent = React.createClass({
getDefaultProps(props){
$('#output').append("Parent getDefaultProps\n");
return{}
},
getInitialState(){
return{
isFoobar: false,
childFoobar : false
};
},
changeProps(){
$('#output').append("\n[props가 바뀔 때]\n\n");
this.setState({
isFoobar: true,
childFoobar :false
});
},
render(){
return(<div className="lParent">
<a href="#" onClick={this.changeProps}>props가 바뀔때</a>
<LifeCycle isFoobar={this.state.isFoobar} childFoobar={this.state.childFoobar}/></div>)
}
});
var reset = function(){ $('#output').empty();}
$('#loading').click(()=>{
if(!isLoaded){
isLoaded=true;
reset();
ReactDOM.render(<LifeCycleParent />, document.getElementById("app"));
}
});
$('#unloading').click(()=>{
if(isLoaded){
isLoaded=false;
reset();
ReactDOM.unmountComponentAtNode(document.getElementById("app"));
}
});
<p>생명주기에 대해 알아봅시다.</p>
<p><a href="#" id="loading">컴포넌트 로딩</a>
<a href="#" id="unloading">컴포넌트 제거</a></p>
<div id="app"></div>
<pre id="output"></pre>
body{background-color:#282a36;color:#f8f8f2; font-size:16px;}
body a{color:#50fa7b;padding-right:20px;}
body pre{background-color: #44475a; font-weight:bold;padding:10px 10px 10px 10px;}
.lParent {height:100px; width:90%;background-color:#6272a4;margin-left:5%;}
.lifecycle {height:50px;width:90%;background-color:#bd93f9;margin-left:5%;}
External resources loaded into this fiddle: