[深入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操作改变根据父组件的数据显示的 ...
随机推荐
- [linux常用命令]查看当前文件夹或该文件夹下文件(夹)的大小
du -sh *(星号表示当前所有文件夹)可以查看当前目录下各个文件夹的大小,-s表示只显示当前文件夹(不加-s你可以看到所有文件夹下的子文件夹的大小,太多了),-h表示以合适的大小查看.(可以用- ...
- Android开发手记(11) 滑动条SeekBar
安卓滑动条的操作特别简单,通过getProgress()可以获得SeekBar的位置,通过setProgress(int progress)可以设置SeekBar的位置.要想动态获取用户对SeekBa ...
- android 瀑布流(图片浏览)
效果图: 瀑流流实现涉及的知识点 1.ScrollView滚动视图,我们这里用的是自定义ScrollView /** * Created by Spring on 2015/11/2. * 自定义Sc ...
- poj1182 并查集
题目连接:http://poj.org/problem?id=1182 基础并查集,需要维护与根节点关系,解析见代码: /* poj 1182 并查集 思路分析:让你分析这些话里面多少假的 只需要用 ...
- 单电机板机模型,f22
视频连接 http://v.youku.com/v_show/id_XMTI5MDEzMzIxMg==.html?from=y1.7-1.2 http://v.youku.com/v_show/id_ ...
- [每日一题] OCP1z0-047 :2013-07-24 子查询――外查询与内查询的执行顺序
一.Oracle的子查询分为两类分别是嵌套子查询和非嵌套子查询.所谓嵌套子查询是指,子查询是一个独立的查询不与外部查询相关,子查询将被先执行,而且只被执行一次,子查询执行完成后,再执行外部的查询,外部 ...
- html表格table设置边框
对于很多初学HTML的人来说,表格<table>是最常用的标签了,但对于表格边框的控制,很多初学者却不甚其解. 一般我们用表格的时候总会给它个border属性,比如:<table b ...
- java8+spring+angularjs 项目应用
最近有写一个电子订单商务网站,使用JAVA8,SPRING,ANGULARJS对项目使用的技术和大家分享. 第一次写博客,哪有不对需要改正的请联系改正. 因为是项目是我给别人做的无法提供源码见谅,我尽 ...
- jquery validation插件使用
首先需要引入jQuery.js和jquery.validate.js 以下面代码为例: <form id="mainform"> <fieldset> &l ...
- phpcms v9联动菜单的调用方法_详解get_linkage函数
phpcms v9联动菜单调用方法[此为内容页调用方法]: {get_linkage($areaid,1,' >> ',1)} 显示效果: phpcms吧 >> 模板下载 &g ...