[深入React] 7.组件生命周期

生命周期一共分三段:初始化,运行中,销毁。按照顺序:
初始化
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.组件生命周期的更多相关文章
- React 之 组件生命周期
React 之 组件生命周期 理解1) 组件对象从创建到死亡它会经历特定的生命周期阶段2) React组件对象包含一系列的勾子函数(生命周期回调函数), 在生命周期特定时刻回调3) 我们在定义组件时, ...
- [React] 多组件生命周期转换关系
前段时间一直在基于React做开发,最近得空做一些总结,防止以后踩坑. 言归正传,React生命周期是React组件运行的基础,本文主要是归纳多组件平行.嵌套时,生命周期转换关系. 生命周期 Reac ...
- React Class组件生命周期
一.react组件的两种定义方式 1.函数组件,简单的函数组件像下面这样,接收Props,渲染DOM,而不关注其他逻辑 function Welcome(props) { return <h1& ...
- react之组件生命周期
四个阶段 初始化 运行中 销毁 错误处理(16.3以后) 初始化 constructor static getDerivedStateFromProps() componentWillMount() ...
- 【JAVASCRIPT】React学习-组件生命周期
摘要 整理组件加载过程,详细见官方文档:https://facebook.github.io/react/docs/react-component.html mount 过程 1)constructo ...
- 【React】组件生命周期
初始化阶段 getDefaultPropos:只调用一次,实力之间共享引用 getInitialState:初始化每个实例特有的状态 componentWillMount:render之前最后一次修改 ...
- React.js 小书 Lesson20 - 更新阶段的组件生命周期
作者:胡子大哈 原文链接:http://huziketang.com/books/react/lesson20 转载请注明出处,保留原文链接和作者信息. 从之前的章节我们了解到,组件的挂载指的是将组件 ...
- React组件生命周期小结
React组件生命周期小结 下面所写的,只适合前端的React.(React也支持后端渲染,而且和前端有点小区别,不过我没用过.) 相关函数 简单地说,React Component通过其定义的几个函 ...
- react学习(6)——关于组件生命周期的问题
在项目开发的过程中,遇到了一个问题: 父组件请求后台数据,收到后将数据以props传给子组件,子组件根据收到数据的不同,显示不同的内容,同时,子组件自身可以根据click操作改变根据父组件的数据显示的 ...
随机推荐
- 通过yum升级CentOS/RHEL最小化安装
1.如果你有安装CentOS / RHEL最小服务器安装,您可能有很多麻烦没有安装包 2.有一种方法来安装所有的包,需要一个基本的服务器,使用yum groupinstall命令 3.从最小的安装基本 ...
- 使用socket实现聊天功能
public class Service { //服务器 public static void main(String[] args) { ServerSocket serverSocket=null ...
- hdu 2104
#include <iostream> using namespace std; int gcd(int a,int b) { return (b?gcd(b,a%b):a); } int ...
- mongodb地理空间计算逻辑
"1/地球半径"是怎么得出的 参考文档如下: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates http:// ...
- An attempt to attach an auto-named database for file
在用VS自带的 .mdf读取(joint)时,报错: Server Error in '/' Application. An attempt to attach an auto-named datab ...
- nginx+tomcat+memcached搭建服务器集群及负载均衡
在实际项目中,由于用户的访问量很大的原因,往往需要同时开启多个服务器才能满足实际需求.但是同时开启多个服务又该怎么管理他们呢?怎样实现session共享呢?下面就来讲一讲如何使用tomcat+ngin ...
- WPFPath素材
放在Viewbox中可固定比例 <!--五角星--> <Canvas Width="100" Height="100"> <Pat ...
- 总结:如何获取同一个DIV里的多个不同子标签的值,并赋值给input?
这个问题说起来简单,但对于新手来说,也着实卡了好久,并且我在网上搜了好久没能找到合适的答案, 于是去博问问了一下,得到许多大神们的帮助与回答,接下来我就总结一下能够实现这个效果的几种方法,既为了自己更 ...
- JDK1.5新特性随手记
1.静态导入 import static 静态导入前写法: public class TestStatic { public static void main(String[] args) { Sys ...
- Css预处理器实践之Sass、Less大比拼
xwei | 2012-07-07 | 网页重构 什么是CSS预处理器? Css可以让你做很多事情,但它毕竟是给浏览器认的东西,对开发者来说,Css缺乏很多特性,例如变量.常量以及一些编程语法,代码难 ...