| 阶段 | 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: 在渲染阶段,后代组件抛出错误后,该声明周期将被调用。他将抛出的错误作为参数,并返回值以更新 statecomponentDidCatch: 后代组件抛出错误后背调用此生命周期,他接受两个参数: error —— 抛出的错误。2. info —— 带有 componentStack key 对象,包括相关组件造成错误的栈信息。componentDidCatch 在提交阶段调用,因此允许执行副作用。 它应于记录错误等情况。
