这一集简单点:生命周期到三个阶段:Mounting(初始化数据期)、Updating(更新期)、Unmounting(销毁期)。
看下面到代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
<script type="text/babel">
var HelloWorld = React.createClass({
/* 一、实例化期 */
getDefaultProps:function () {
console.log('1. getDefaultPros 获取默认的props');
return{
name:"SKHon"
}
},
getInitialState:function () {
console.log("2. getInitialState 设置状态机");
return{
}
},
componentWillMount:function() {
console.log('3. componentWillMout 完成首次渲染前调用【注】这是在渲染前,修改state的最后一次机会')
},
render:function () {
return(
<div>
<button onClick={this.showName}>点击</button>
<div>{this.props.name}</div>
</div>
)
},
componentDidMount:function() {
console.log('4. componentDidMount render渲染后的操作 【注】react运行在服务端时,该方法不被调用' )
},
showName:function () {
console.log(this.props.name);
},
/* 二、存在期 (也叫修改期) */
componentWillReceiveProps:function(newProps) {
this.props.name="aaa";
console.log('组件渲染后,当组件接收到新的props时被调用')
},
shouldComponentUpdate:function(newProps, newState) {
/*组件渲染后(即执行完render),接收到新的state或props时被调用*/
return true;
},
componentWillUpdate:function(nextProps, nextState) {
console.log('即将发生重新渲染前调用该方法');
},
componentDidUpdate:function(prevProps, prevState) {
console.log('在组件更新之后操作DOM元素调用该方法')
},
/* 三、销毁期 */
componentWillUnmount:function() {
console.log('组件被卸载前调用')
}
})
ReactDOM.render(
<HelloWorld />,
document.getElementById("app")
)
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>