阶段 | v15 | v16.8 |
---|---|---|
挂载阶段 | constructor | constructor |
componentWillMount | getDerivedStateFromProps | |
render | render | |
componentDidMount | componentDidMount | |
– | – | – |
更新阶段 | componentWillReceiveProps | getDerivedStateFromProps |
shouldComponentUpdate | shouldComponentUpdate | |
componentWillUpdate | render | |
render | getSnapshotBeforeUpdate | |
componentDidUpdate | componentDidUpdate | |
– | – | – |
卸载阶段 | componentWillUnmount | componentWillUnmount |
– | – | – |
异常处理 | getDerivedStateFromError | |
componentDidCatch |
v15 --> v16
废弃三个生命周期(未删除,UNSAVE_前缀):componentWillMount
、componentWillUpdate
、componentWillReceiveProps
新增了三个生命周期:getDerivedStateFromProps
、getSnapshotBeforeUpdate
、componentDidCatch
getDerivedStateFromProps
这是个静态方法,此方法必须要有返回值,返回一个对象,或者返回 null,返回 null 则不更新任何内容。
当我们接收到新的属性想去修改state, 可以使用 getDerivedStateFromProps
getSnapshotBeforeUpdate(prevProps,prevState)
这个在render方法之后,Update之前调用,有两个参数prevProps,prevState,表示之前的props和之前的state,这个函数有一个返回值,会作为第三个参数传给componentDidUpdate,如果你不想要返回值,可以返回null,此生命周期必须与componentDidUpdate搭配使用(新增生命周期)。
static getDerivedStateFromError
: 此声明周期会在渲染阶段后代组件抛出错误后被调用,他将抛出的错误作为参数,并返回一个值以更新 state
componentDidCatch
: 此生命周期在后代组件抛出错误后背调用,他接受两个参数: error —— 抛出的错误。2. info —— 带有 componentStack key 的对象,其中包含有关组件引发错误的栈信息。componentDidCatch 会在“提交”阶段被调用,因此允许执行副作用。 它应该用于记录错误之类的情况。
图示: