react组件生命周期介绍
概念:在组件创建、到加载到页面上运行、以及组件被销毁的过程中,总是伴随着各种各样的事件,这些在组件特定时期,触发的事件,统称为组件的生命周期;
1. 装载过程(mont),组件创建阶段的生命周期函数,就是组件在第一次在DOM树中渲染的过程,有一个显著的特点:创建阶段生命周期函数在组件的一辈子中,只执行一次;
1.1 constructor
就是Es6里的构造函数,创建一个组件类的实例,在这一过程中我们要进行两步操作:初始化state,绑定成员函数的this环境
2.2 render
不夸张的说render是React组件中最为重要的一个函数。这个react中唯一不可忽略的函数,在render函数中,只能有一个父元素。
3.3 componenWillMonunt和componentDidMount
这两个函数分别在render前后执行,componentWillMonut显得有些鸡肋,还没有任何东西展示,操作完全可以提前到constructor中来进行
但是componentDidMount函数作用就大得多,由于这一过程通常只能在浏览器端调用,所以我们在这里获取异步数据,而且在componentDidMount调用的时候,组件已经被装载到DOM树上了,还有,可以在这里执行其他库的代码,比如Jquery。
2.更新过程(update),组件被重新渲染的过程,也有一个显著的特点,根据组件的state和props的改变,有选择性的触发0次或多次;
2.1 componentWillReceiveProps(nextProps)
并不是只有在props发生改变的时候才会被调用,实际上只要是父组件的render函数被调用,render里面被渲染的子组件就会被更新,不管父组件传给子组件的props有没有被改变,都会触发子组件的componentWillReceiveProps过程,但是,this.setState方法的触发过程不会调用这个函数,因为这个函数适合根据新的props的值来计算出是不是要更新内部状态的state。
2.2 shouldComponentUpdate(nextProps, nextState)
这个函数的重要性,仅次于render,render函数决定了改渲染什么,而shouldComponentUpdate决定了不需要渲染什么**,这两位大佬都需要返回函数,这一过程可以提高性能,忽略掉没有必要重新渲染的过程
2.3 componentWillUpdate和componentDidUpdate
和装载过程不同,这里的componentDidUpdate,既可以在浏览器端执行,也可以在服务器端执行
3. 卸载阶段
实际中也很少用到,这里只有一个componentWillUnmount
import React, { Component } from 'react'
export default class Life extends Component {
//创建阶段
//constructor()默认调用,只能调用一次(方便初始化数据)
constructor(props){
super();
console.log("constructor...")
//设置初始化状态
this.state={
num:0,
isStart:false,
}
}
//复选框按钮事件
handelCheck(e){
this.setState({
//获取事件源
isStart:e.target.checked,
})
}
//渲染前调用(主要用于修改state状态,也可使用Ajax获取数据)
componentWillMount(){
console.log("componentWillMount...")
}
//渲染函数
render() {
return (
<div>
<h3>往这看</h3>
<p><input type="checkbox" onChange={this.handelCheck.bind(this)} />看按钮是否能用</p>
<button onClick={this.handelBtn.bind(this)}>来喽来喽</button>
<p>数据:{this.state.num}</p>
</div>
)
}
//点击按钮事件
handelBtn(){
console.log('更新数据....')
let i=this.state.num;
i++;
this.setState({
num:i,
})
}
//组件渲染后调用,有且只调用一次(适用于网络延迟,操作处理)
componentDidMount(){
console.log("componentDidMount...")
}
//是否同意更新
shouldComponentUpdate(){
console.log('shouldComponentUpdate.....');
return this.state.isStart;
}
//不阻止更新的话,在render之前调用(组件即将被更新)
componentWillUpdate(){
console.log('componentWillUpdate....');
}
//更新后,render渲染结束调用(组件渲染完成之后调用)
componentDidUpdate(){
console.log('componentDidUpdate.....');
}
}