组件的生命周期可分为三个状态:
- Mounting:组件挂在,已插入真实DOM
- Updating:组件更新,正在被重新渲染
- Unmounting:组件移除,已移除真实DOM
Mounting/组件挂载相关
- componentWillMount
组件将要挂载。在render之前执行,但仅执行一次,即使多次重复渲染该组件,或者改变组件的state也不会有影响。 - componentDiaMount
组件已经挂载。在render之后执行,同一个组件重复渲染只执行一次。
Updating/组件更新相关
- componentWillReceiveProps(object nextProps)
已加载组件收到新的props之前调用,注意组件初始化渲染时则不会执行。 - shouldComponentUpdate(object nextProps,object nextState)
组件判断是否重新渲染时调用。该接口实际是在组件接收到了新的props或者新的state的时候会立即调用,然后通过返回值true或false进行判断。 - componentWillUpdate(object nextProps,object nextState)
组件将要更新。 - componentDidUpdate(object prevProps,object prevState)
组件已经更新。
Unmounting/组件移除相关
- componentWillUnmount
在组件要被移除之前的时间点触发,可以利用该方法来执行一些必要的组件清理
生命周期中与props和state相关
- getDefaultProps 设置props属性默认值
- getInitialState 设置state属性初始值
组件的生命周期可分为四个阶段:
- 创建
- 实例化
- 更新
- 销毁
生命周期各阶段介绍
var Demo = React.createClass({
/*
一、创建阶段
流程:
只调用getDefaultProps方法
*/
getDefaultProps:function(){
console.log("getDefaultProps");
return {};
//需要返回一个对象,这里返回空
//return {name:Tom,age:15};
//this.props.name
},
/*
二、实例化阶段
流程:
getInitialState
componentWillMount
render
componentDiaMount
*/
getInitialState:function(){
// 设置this.state的默认值
console.log("getInitialState");
return null;
},
componentWillMount:function(){
// 在render之前调用
console.log("getInitialState");
},
render:function(){
// 渲染并返回一个虚拟DOM
console.log("render");
return
<div>
Hello World
</div>
},
componentDiaMount:function(){
// 在render之后调用
// 在该方法中,React会使用render方法返回的虚拟DOM对象创建真实的DOM结构
// 可以在这个方法中读取DOM节点
console.log("componentDiaMount");
},
/*
三、更新阶段
流程:
componentWillReceiveProps
shouldComponentUpdate //如果返回值是false,后三个方法不执行
componentWillUpdate
render
componentDiaUpdate
*/
componentWillReceiveProps:function(){
console.log("componentWillReceiveProps");
},
shouldComponentUpdate:function(){
console.log("shouldComponentUpdate");
return true;
},
componentWillUpdate:function(){
console.log("componentWillUpdate");
},
componentDiaUpdate:function(){
console.log("componentDiaUpdate");
},
/*
四、销毁阶段
流程:
componentWillUnmount:
*/
componentWillUnmount:function(){
console.log("componentWillUnmount");
}
});
// 第一次创建并加载组件
ReactDOM.render(
<Demo />,
document.getElementById('id')
);
// 重新渲染组件
ReactDOM.render(
<Demo />,
document.getElementById('id')
);
// 移除组件
ReactDOM.unmoutComponentAtNode(document.getElementById('id'));
> 执行结果:
> getDefaultProps
> getInitialState
> componentWillMount
> render
> componentDiaMount
> componentWillReceiveProps
> shouldComponentUpdate
> componentWillUpdate
> render
> componentDiaUpdate
> componentWillUnmount
文章来自蓝鸥React教程视频