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

初始化

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. MVC的Model层中的一些便签

    由于自己重新接触MVC,所以把Model层里的一些标签给记录下来,方便自己的使用. 这些是自己目前试用过的一些,在以后的工作中我会接着补充进去新的内容

  2. Wcf+EF框架搭建实例

    一.最近在使用Wcf创建数据服务,但是在和EF框架搭建数据访问时遇到了许多问题 下面是目前整理的基本框架代码,经供参考使用,源代码地址:http://git.oschina.net/tiama3798 ...

  3. JS相关链接

    给开发者提供的 35 款 JavaScript 图形图表库: http://news.cnblogs.com/n/201518/ 主题:[前端必看]JavaScript推荐资料合集: http://w ...

  4. form表单提交

    1.form表单提交.html页面失败 <%--客户端form--%> <form id="form2" action="LoginOne.html&q ...

  5. DIV布局之道一:DIV块的水平并排、垂直并排

    DIV布局网页元素的方式主要有三种:平铺(并排).嵌套.覆盖(遮挡).本文先讲解平铺(并排)方式. 1.垂直平铺(垂直排列) 请看如下代码 CSS部分: CSS Code复制内容到剪贴板 .lay1{ ...

  6. 历史执行Sql语句性能分析 CPU资源占用时间分析

    SELECT     HIGHEST_CPU_QUERIES.PLAN_HANDLE,     HIGHEST_CPU_QUERIES.TOTAL_WORKER_TIME,     Q.DBID,   ...

  7. git add相关

    git add -A stages All git add . stages new and modified, without deleted git add -u stages modified ...

  8. 小学生之解析XML应用

    1.什么是XML? 解析:XML:Extensible Markup Language(可扩展标记语言) HTML:HyperLink Text  Markup Language(超文本标记语言)   ...

  9. THINK PHP U的用法

    public function index(){ //$db=new \Think\Model(); //$db=M('msg'); //$result=$db->query("sel ...

  10. javascript 关于闭包的知识点

    javascript 关于闭包的认识 概念:闭包(closure)是函数对象与变量作用域链在某种形式上的关联,是一种对变量的获取机制. 所以要大致搞清三个东西:函数对象(function object ...