<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="./build/react.js" charset="utf-8"></script>
<script src="./build/react-dom.js" charset="utf-8"></script>
<script src="./build/browser.min.js" charset="utf-8"></script>
</head>
<body>
<div id="container">
</div>
</body>
<script type="text/babel">
/*
生命周期三个状态:
Mounting:组件挂载,已插入真实DOM
Updating:组件更新,正在被重新渲染
Unmounting:组件移出,已移出真实DOM
生命周期四个阶段:
创建、实例化、更新、销毁
*/
var Demo = React.createClass({
/*-----------------------------------------------------------------------------*/
// 1.创建阶段:只调用getDefaultProps方法
getDefaultProps: function(){
// 在创建类的时候被调用,设置this.props的默认值
console.log("getDefaultProps");
return{};
},
/*-----------------------------------------------------------------------------*/
// 2.实例化阶段:getInitialState->componentWillMount->render->componentDidMount
getInitialState: function() {
//设置this.state的默认值
console.log("getInitialState");
return null;
},
componentWillMount: function() {
//组件将要挂载,在render之前调用,即使多次重复渲染,或者改变组件的state,仅执行一次
console.log("componentWillMount");
},
render: function() {
//用来渲染并返回一个虚拟dom
console.log("render");
return <div>hello react</div>
},
componentDidMount: function() {
//组件已经挂载,render之后调用,在该方法中,react会使用render方法返回的虚拟DOM对象创建真实的DOM结构
//可以在这个方法中获取DOM节点,同一个组件重复渲染只执行一次
console.log("componentDidMount");
},
/*-----------------------------------------------------------------------------*/
//3.更新阶段:componentWillReceiveProps->shuldComponentUpdate->componentWillUpdate(如果返回值是false,后三个方法不执行)->render->componentDidUpdate
componentWillReceiveProps: function() {
//componentWillReceiveProps(object nextProps)
//已加载组件收到新的props之前调用,注意组件初始化渲染时不会执行
console.log("componentWillReceiveProps");
},
shouldComponentUpdate: function() {
//是否需要重新渲染组件,接收到了新的props或者新的state的时候立即调用
console.log("shouldComponentUpdate");
return true;
},
componentWillUpdate: function() {
//组件将要更新
console.log("componentWillUpdate");
},
componentDidUpdate: function() {
//组件已经更新
console.log("componentDidUpdate");
},
/*-----------------------------------------------------------------------------*/
//4.销毁阶段:componentWilUnmount
componentWilUnmount: function() {
//在组件将要被移除之前的时间点触发
console.log("componentWilUnmount");
},
})
//第一次创建并加载组件
ReactDOM.render(
<Demo/>,
document.getElementById("container")
)
//重新渲染
ReactDOM.render(
<Demo/>,
document.getElementById("container")
)
//移除组件
ReactDOM.unmountComponentAtNode(document.getElementById("container"));
</script>
</html>