Demo09 - 组件的生命周期 by zuojj at 01 Jul 2016
React 的组件的生命周期分为实例化、存在期、销毁&清理期,不同阶段会触发不同的方法,可以通过F12快捷键,输入用户名称,console控制台查看
HTML
<div id="form-outer"></div>
JAVASCRIPT
/**
+ console.log查看组件的生命周期!!!
*/
var Form = React.createClass({
// ==========实例化===========
getDefaultProps: function() {
console.log('getDefaultProps');
},
getInitialState: function() {
console.log('getInitialState');
return {
username: 'Benjamin-zuo'
};
},
componentWillMount: function() {
console.log('componentWillMount');
},
render: function() {
console.log('render');
return (
<div class="input-outer">
<input type="text" value={this.state.username} onChange={this.handleChange} />
<input type="button" value="remove" onClick={this.handleClick}/>
</div>
);
},
componentDidMount: function() {
console.log('componentDidMount');
},
// =========存在期===========
// 已加载组件收到新的参数时调用,比如:组件的props通过父组件来更改时
componentWillReceiveProps: function() {
console.log('componentWillReceiveProps');
},
// 组件判断是否重新渲染时调用
shouldComponentUpdate: function() {
console.log('shouldComponentUpdate');
return true;
},
// 组件更新前调用
componentWillUpdate: function() {
console.log('componentWillUpdate');
},
// 组件更新完调用
componentDidUpdate: function() {
console.log('componentDidUpdate');
},
// ===========销毁& 清理期==========
componentWillUnmount: function() {
console.log('componentWillUnmount');
},
handleClick: function() {
document.getElementById('form-outer').innerHTML = '';
},
handleChange: function(ev) {
this.setState({
username: ev.target.value
})
}
});
ReactDOM.render(<Form/>, document.getElementById('form-outer'));