组件的生命周期

参考
https://www.tuicool.com/articles/nu6zInB

/* 生命周期介绍
1.组件的生命周期,分成三个状态:
Mounting :组件挂载,已插入真是DOM
Updating :组件更新,正在被重新渲染
Unmouting :组件移出,已移出真是DOM

2.组件的生命周期,分为四个阶段
创建, 实例化, 更新, 销毁

*/


/*方法
1.Mounting 组件挂载相关方法
(1)componentWillMount
组件将要挂载,在render之前执行,但仅执行一次,及时多次重复渲染该组件,或者改变了组件的state
(2)componentDidMount
组件已经挂载,在render之后执行,同一个组件重复渲染只执行一次

2.Updating 组件更新相关方法:
(1)componentWillReceiveProps(object nextProps)
已加载组件收到新的props之前调用,注意组件化渲染时,则不会执行
(2)shouldComponentUpdate(object nextProps,object nextState)
组件判断是否重新渲染时调用.该接口实际是在组件接收到了新的props或者新的state 的时候,会理解调用,然后通过
(3)componentWillUpdate(object nextProps,object nextState)
组件将要更新
(4)componentDidUpdate(object prevProps,object prevState)
组件已经更新

3.Unmounting 组件移除相关
(1)componentWillUnmount
在组件将要被移除之前的时间点出发,可以利用该方法来执行一些必要的清理组件

4.生命周期中与props和state相关方法
(1)getDefaultProps 设置props属性默认值
(2)getInitialState 设置state属性初始值

*/

/*

生命周期各个阶段

*/

var Demo = React.createClass({
/*
一.创建阶段
流程:
只调用getDefaultProps方法

*/
getDefaultProps:function () {
//在创建类的时候被调用,设置this.props的默认值
console.log("getDeafultProps");
return {};
},
/*
二.实例化阶段
流程:
getInitialState
componentWillMount
render
componentDidMount

*/

getInitialState:function () {
console.log("getInitialState")
return null;
},
componentWillMount:function () {
//在render之前调用
console.log("componentWillMount")

},
render:function () {
//渲染并返回一个虚拟DOM
console.log("render")
return <div>hello React</div>
},

componentDidMount:function () {
//在render之后调用
//在该方法中,React会使render方法返回的虚拟DOM对象创建真实的DOM结构
console.log("componentDidMount");

},
/*
三. 更新阶段
流程:
componentWillReceiveProps
shouldComponetUpdate 如果返回值是false, 后面三个方法不执行
componentWillUpdate
render
componentDidUpdate

*/
componentWillReceiveProps:function () {
console.log("componentWillReceiveProps")
},
shouldComponentUpdate:function () {
console.log("shouldComponentUpdate")
return true;//返回false, 则不执行更新
},
componentWillUpdate:function () {
console.log("componentWillUpdate")
},
componentDidUpdate:function () {
console.log("componentDidUpdate")
},

/*
四.销毁阶段
流程:
componentWillUnmount

*/
componentWillUnmount:function () {
console.log("componentWillUnmount")
}

});

//渲染,第一次创建并加载组件
ReactDOM.render(
<Demo/>,
document.getElementById("container")
);
//重新渲染
ReactDOM.render(
<Demo/>,
document.getElementById("container")
);
//移除组件
ReactDOM.unmountComponentAtNode(document.getElementById("container"));
posted @ 2017-11-30 22:27  Da雪山  阅读(445)  评论(0编辑  收藏  举报