参照文章:react生命周期的基本用法
1、constructor
可以获取到父组件传下来的参数。
只要组件存在constructor,就必要要写super,否则this指向会错误。
2、componentWillMount 组件将要挂载
3、componentDidMount 组件渲染完成
4.componentWillReceiveProps (nextProps)
componentWillReceiveProps在接受父组件改变后的props需要重新渲染组件时用到的比较多
它接受一个参数:nextProps
通过对比nextProps和this.props,将nextProps setState为当前组件的state,从而重新渲染组件。
5.shouldComponentUpdate(nextProps,nextState)
唯一用于控制组件重新渲染的生命周期,由于在react中,setState以后,state发生变化,组件会进入重新渲染的流程,(暂时这么理解,其实setState以后有些情况并不会重新渲染,比如数组引用不变)在这里return false可以阻止组件的更新
因为react父组件的重新渲染会导致其所有子组件的重新渲染,这个时候其实我们是不需要所有子组件都跟着重新渲染的,因此需要在子组件的该生命周期中做判断
6.componentWillUpdate (nextProps,nextState)
shouldComponentUpdate返回true以后,组件进入重新渲染的流程,进入componentWillUpdate,这里同样可以拿到nextProps和nextState
7.render函数
render函数会插入jsx生成的dom结构,react会生成一份虚拟dom树,在每一次组件更新时,在此react会通过其diff算法比较更新前后的新旧DOM树,比较以后,找到最小的有差异的DOM节点,并重新渲染
8、componentDidUpdate(prevProps,prevState)
组件更新完毕后,react只会在第一次初始化成功会进入componentDidmount,之后每次重新渲染后都会进入这个生命周期,这里可以拿到prevProps和prevState,即更新前的props和state。
9、componentWillUnmount ()
基本使用,从以下的一个实验中看出,基本的三个函数执行顺序就是coustructor, componentwillmount, componentDidMount。
其余的一些钩子函数之后再做深入了解。

code:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
console.log('this is in constructor method.');
this.state = {
date: new Date()
};
}
componentWillMount () {
console.log('this is in componentWillMount method.');
}
componentDidMount () {
console.log('this is in componentDidMount method.');
}
componentWillReceiveProps (nextProps) {
console.log('this is in componentWillReceiveProps method.');
}
shouldComponentUpdate (nextProps,nextState) {
console.log('this is in shouldComponentUpdate method.');
}
componentWillUpdate (nextProps,nextState) {
console.log('this is in componentWillUpdate method.');
}
componentDidUpdate (prevProps,prevState) {
console.log('this is in componentDidUpdate method.');
}
render() {
return (
<div>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
componentWillUnmount () {
console.log('this is in componentWillUnmount method.');
}
}
export default App;