1.React16新的生命周期弃用了componentWillMount、componentWillReceivePorps,componentWillUpdate

2.新增了getDerivedStateFromProps、getSnapshotBeforeUpdate来代替弃用的三个钩子函数(componentWillMount、componentWillReceivePorps,componentWillUpdate)

3.React16并没有删除这三个钩子函数,但是不能和新增的两个钩子函数(getDerivedStateFromProps、getSnapshotBeforeUpdate)混用。

注意:React17将会删除componentWillMount、componentWillReceivePorps,componentWillUpdate

4.React16新增了对错误处理的钩子函数(componentDidCatch)

一、React旧版本生命周期

React旧版本与React16中生命周期的区别_java

1、子组件(child conponent)首次挂载

依次触发了Child组件的:

constructor,

componentWillMount,

render,

componentDidMount。

2、子组件props发生改变

(1)shouldComponentUpdate返回true

依次调用了Child组件的:

componentWillReceiveProps,

shouldComponentUpdate,

componentWillUpdate,

render,

componentDidUpdate。

(2)shouldComponentUpdate返回false

只调用了Child组件的:

componentWillReceiveProps,

shouldComponentUpdate。

3、子组件state发生改变

依次调用了Child组件的:

shouldComponentUpdate,

componentWillUpdate,

render,

componentDidUpdate。

与2相比,3中缺少了componentWillReceiveProps,这是因为componentWillReceiveProps在组件接收到一个新的props时才会被调用(注:这个方法在第一次渲染时不会被调用)。

二、React16生命周期

React旧版本与React16中生命周期的区别_java_02

1、子组件(child component)首次被挂载

依次触发了Child组件的:

constructor,

getDerivedStateFromProps,

render,

componentDidMount。

2、子组件props发生改变

(1)shouldComponentUpdate返回true

依次调用了Child组件的:

getDerivedStateFromProps,

shouldComponentUpdate,

render,

getSnapshotBeforeUpdate,

componentDidUpdate。

(2)shouldComponentUpdate返回false

只调用了Child组件的:

getDerivedStateFromProps,

shouldComponentUpdate。

3、子组件state发生改变

(1)shouldComponentUpdate返回true

依次调用了Child组件的:

getDerivedStateFromProps,

shouldComponentUpdate,

render,

getSnapshotBeforeUpdate,

componentDidUpdate。

(2)shouldComponentUpdate返回false

依次调用了Child组件的:

getDerivedStateFromProps,

shouldComponentUpdate。

与2中修改子组件(child component)的props时相同。