上图

现在直接看图可能会感觉比较复杂,但是不要慌张
Initialization:初始化阶段。Mounting: 挂载阶段。Updation: 更新阶段。Unmounting: 销毁阶段
例如(初始化和挂载阶段):
class Text extends Component {
constructor(props) {
super(props);
this.state = { }
}
componentWillMount(){
console.log('will -------')
}
componentDidMount(){
console.log('did -------')
}
render() {
return ( );
}
}Initialization:初始化阶段。constructor我们叫构造函数,它是ES6的基本语法。虽然它和生命周期函数的性质一样,但不能认为是生命周期函数。Mounting: 挂在阶段。componentWillMount: 在组件即将被挂载到页面的时刻执行。render: 页面state或props发生变化时执行。componentDidMount: 组件挂载完成时被执行。
例如(更新和销毁阶段):
//Test1
class Test1 extends Component {
constructor(props) {
super(props);
this.state = { }
}
componentWillMount(){
console.log('will -------')
}
componentDidMount(){
console.log('did -------')
}
shouldComponentUpdate(){
console.log('1 shouldComponentUpdate -------')
return true
}
componentWillUpdate(){
console.log('2 componentWillUpdate -------')
}
componentDidUpdate(){
console.log('4 componentDidUpdate -------')
}
render() {
console.log('3 render --------')
return ( <Test2 /> );
}
}//Test2
class Test2 extends Component {
constructor(props) {
super(props);
this.state = { }
}
//组件第一次存在于Dom中,函数不会被执行。 如果已经存在Dom中,函数才会被执行
componentWillReceiveProps(){
console.log('child componentWillReceiveProps -------')
}
componentWillUnmount(){
console.log('end componentWillUnmount -------')
}
render() { return ( ); }}Updation: 更新阶段。shouldComponentUpdate函数会在组件更新之前,自动被执行。
它要求返回一个布尔类型的结果,必须有返回值,例子就直接返回的 truecomponentWillUpdate在组件更新之前,但shouldComponenUpdate之后被执行。但是如果shouldComponentUpdate返回false,这个函数就不会被执行了。componentDidUpdate在组件更新之后执行,它是组件更新的最后一个环节。-
componentWillReceiveProps在子组件接收了props,这时候函数就可以被执行了。 Unmounting: 销毁阶段componentWillUnmount,它是在组件去除时执行
可能大家在使用低版本的React 的生命周期时,日志会出现警告。

可做参考:segmentfault.com/a/119000002…
建议:大家自己敲一敲代码 ,加深记忆力,又可以对生命周期的理解更深一层。
前端mock线上模拟:EasyMock
推荐npm 库:
- axios(ajax)请求Mock数据
- react-transition-group 动画库