生命周期一共分三段:初始化,运行中,销毁。按照顺序:

初始化

getDefaultProps():Object

全局只会调用一次,为当前类生成的默认props,会被父组件传入的同名props覆盖。

getInitialState():Object

为当前组件生成最初的state,此时可以访问this.props

componentWillMount

mount直译为挂载,就是组件在页面中有对应的DOM。

render

严格意义上render不是一个生命周期环节,它只是一个生成虚拟DOM的方法。需要返回一个虚拟DOM树或者null

componentDidMount

组件已经被挂载DOM,生成了this.refs,也是初始化中唯一可以发ajax的环节。

整个初始化阶段结束。

运行中

运行中就是组件(挂载)在页面上的阶段。当组件自己setState或者父辈容器setState之后会触发一次update

componentWillReceiveProps(newProps):void

  • 父组件update后会render出一个本组件的新虚拟DOM
  • React将新虚拟DOM的props,赋值给本组件的this.props
  • 在赋值之前先调用本方法,参数是新的props

主要用于更新由props派生的state,这种情况下本环节就 很重要 ,比如以userId为参数的头像组件:

var Avatar = React.createClass({
getInitialState:function(){
return {
avatar_url:''
};
},
componentDidMount:function(){
var self = this;
this.avatarAjax = $.get('/get_avatar/',{
id:this.props.id
},function(url){
self.avatarAjax = null;
this.setState({
avatar_url:url
});
});
},
componentWillReceiveProps:function(newProps){
if(newProps.id!==this.props.id){
if(this.avatarAjax){
this.avatarAjax.abort();
}
this.avatarAjax = $.get('/get_avatar/',{
id:this.props.id
},function(url){
self.avatarAjax = null;
this.setState({
avatar_url:url
});
});
}
},
render:function(){
return _('image',{
src:this.state.avatar_url
},null);
}
});

优化:

var Avatar = React.createClass({
getInitialState:function(){
return {
avatar_url:''
};
},
componentDidMount:function(){
this.update(this.props);
},
componentWillReceiveProps:function(newProps){
if(newProps.id!==this.props.id){
this.update(newProps);
}
},
render:function(){
return _('image',{
src:this.state.avatar_url
},null);
},
update:function(props){
var self = this;
$.get('/get_avatar/',{
id:props.id
},function(url){
self.avatarAjax = null;
this.setState({
avatar_url:url
});
});
},
});

shouldComponentUpdate():bool

主要用于性能优化,初期可以不必理会。用于告诉React对于本次update,本组件不需要重新update

componentWillUpdate

render

componentDidUpdate

一次更新结束。

销毁阶段

componentWillUnmount

销毁只有这一个环节,组件unmount后就销毁了,将不再重新mount到其他DOM上。

var i = 0;
var content = document.getElementById('content');
var Item = React.createClass({
getInitialState:function(){
// 赋予对象 id
if(!this.itemId){
this.itemId = ++i;
}
console.log('initState: '+ this.itemId);
return {};
},
componentWillReceiveProps:function(newProps){
if(this.props.id!==newProps.id)
console.log(this.props.id,newProps.id);
},
render:function(){
return _('div',null,this.props.id);
},
componentWillUnmount:function(){
console.log('unmount: '+this.itemId);
}
}); var List = React.createClass({
componentWillUnmount:function(){
console.log('list unmount');
},
render:function(){
return _('div',null,
this.props.data.map(function(id,i){
return _(Item,{
key:i,
id:id
});
}
));
}
}); ReactDOM.render(_(List,{data:[1,2,3]}),content);
setTimeout(function() {
ReactDOM.render(_(List,{data:[1,2]}),content);
setTimeout(function() {
ReactDOM.render(_(List,{data:[1,2,3]}),content);
}, 10);
}, 10);
/* 输出为
initState: 1
initState: 2
initState: 3
unmount: 3
initState: 4
*/

这个阶段主要用来解绑已经绑定的事件,取消发出的异步请求(timeout,ajax等)。防止setState被再次调用,并释放内存。

头像组件示例:

var Avatar = React.createClass({
getInitialState:function(){
return {
avatar_url:''
};
},
componentDidMount:function(){
this.update(this.props);
},
componentWillReceiveProps:function(newProps){
if(newProps.id!==this.props.id){
this.update(newProps);
}
},
render:function(){
return _('image',{
src:this.state.avatar_url
},null);
},
componentWillUnmount:function(){
if(self.avatarAjax){
self.avatarAjax.abort();
self.avatarAjax = null;
}
},
update:function(props){
var self = this;
if(this.avatarAjax){
this.avatarAjax.abort();
}
this.avatarAjax = $.get('/get_avatar/',{
id:props.id
},function(url){
self.avatarAjax = null;
this.setState({
avatar_url:url
});
});
},
});

[深入React] 7.组件生命周期的更多相关文章

  1. React 之 组件生命周期

    React 之 组件生命周期 理解1) 组件对象从创建到死亡它会经历特定的生命周期阶段2) React组件对象包含一系列的勾子函数(生命周期回调函数), 在生命周期特定时刻回调3) 我们在定义组件时, ...

  2. [React] 多组件生命周期转换关系

    前段时间一直在基于React做开发,最近得空做一些总结,防止以后踩坑. 言归正传,React生命周期是React组件运行的基础,本文主要是归纳多组件平行.嵌套时,生命周期转换关系. 生命周期 Reac ...

  3. React Class组件生命周期

    一.react组件的两种定义方式 1.函数组件,简单的函数组件像下面这样,接收Props,渲染DOM,而不关注其他逻辑 function Welcome(props) { return <h1& ...

  4. react之组件生命周期

    四个阶段 初始化 运行中 销毁 错误处理(16.3以后) 初始化 constructor static getDerivedStateFromProps() componentWillMount() ...

  5. 【JAVASCRIPT】React学习-组件生命周期

    摘要 整理组件加载过程,详细见官方文档:https://facebook.github.io/react/docs/react-component.html mount 过程 1)constructo ...

  6. 【React】组件生命周期

    初始化阶段 getDefaultPropos:只调用一次,实力之间共享引用 getInitialState:初始化每个实例特有的状态 componentWillMount:render之前最后一次修改 ...

  7. React.js 小书 Lesson20 - 更新阶段的组件生命周期

    作者:胡子大哈 原文链接:http://huziketang.com/books/react/lesson20 转载请注明出处,保留原文链接和作者信息. 从之前的章节我们了解到,组件的挂载指的是将组件 ...

  8. React组件生命周期小结

    React组件生命周期小结 下面所写的,只适合前端的React.(React也支持后端渲染,而且和前端有点小区别,不过我没用过.) 相关函数 简单地说,React Component通过其定义的几个函 ...

  9. react学习(6)——关于组件生命周期的问题

    在项目开发的过程中,遇到了一个问题: 父组件请求后台数据,收到后将数据以props传给子组件,子组件根据收到数据的不同,显示不同的内容,同时,子组件自身可以根据click操作改变根据父组件的数据显示的 ...

随机推荐

  1. linux定时任务2-at命令

    定时执行命令: [root@rheltest1 ~]# at now + 1 minute //一分钟后执行下面的任务 at> date >> /tmp/test_date.log ...

  2. 如何缩减Try{}Catch{}Finally{}代码----定义一个公用的Try{}Catch{}Finally{}

    public class Process { public Process() { } public static void Execute(Action action) { try { //ACTI ...

  3. 对于没有Command属性时,怎么来达到相同的效果

    控件是第三方Telerik控件  CellEditEnded事件想写成Command{Binding CellEditEndedCommand}  这样的效果如下代码 需要引用 System.Wind ...

  4. MySQL 行子查询

    MySQL 行子查询 行子查询是指子查询返回的结果集是一行 N 列,该子查询的结果通常是对表的某行数据进行查询而返回的结果集. 一个行子查询的例子如下: SELECT * FROM table1 WH ...

  5. c#之线程入门

    C#支持通过多线程并行地执行代码,一个线程有它独立的执行路径,能够与其它的线程同时地运行.一个C#程序开始于一个单线程,这个单线程是被CLR和操作系统(也称为“主线程”)自动创建的,并具有多线程创建额 ...

  6. zepto源码研究 - ajax.js($.ajax具体流程分析)

    简要:$.ajax是zepto发送请求的核心方法,$.get,$.post,$.jsonp都是封装了$.ajax方法.$.ajax将jsonp与异步请求的代码格式统一起来,内部主要是先处理url,数据 ...

  7. rails 中 create, new, build, save 的用法以及误区汇总

    自己很初级,初级的不能再初级,所以初次接触rails的时候,对于里面的create,new,build等方法不是很了解,用的很混乱,导致经常出现不必要的bug,很苦恼,决定,总结一下,结合网上已有资源 ...

  8. ios nslog 打印字典为中文

    #import <Foundation/Foundation.h> @implementation NSDictionary (Log) - (NSString *)description ...

  9. 【PHP】新浪、淘宝的地区 API调用

    /推荐使用新浪的: $ch = curl_init(); $url = "http://ip.dpool.sina.com.cn/iplookup/iplookup.php?format=j ...

  10. phpcms v9中模板标签使用及联动菜单

    {template "content","header"} 调用根目录下phpcms\template\content\header文件 {charset} 字 ...