React(17.0版本)生命周期概述

React17版本的生命周期概述。

挂载

示例代码在下方。

当组件实例被创建并插入DOM的时候,其生命周期被调用顺序如下:

  1. constructor(props) - 初始化state和为事件处理函数绑定实例;
  2. static getDerivedStateFromProps(props, state) - 当state的值在任何时候都取决于props时使用,返回一个对象来更新state,返回null则不更新;
  3. render() - 渲染React组件;
  4. componentDidMount() - 组件挂载后调用,一个生命周期内仅一次;
    25c6aad22567e8309665ac3318ff93c2.jpg

更新

当组件的props或state发生变化时会触发更新。组件更新的生命周期顺序如下:

  1. static getDerivedStateFromProps(props, state);
  2. shouldComponentUpdate(nextProps, nextState) - 根据更新后的state或props判断是否重新渲染DOM,返回值为布尔值,常用来性能优化;
  3. render();
  4. getSnapshotBeforeUpdate(prevProps, prevState) - 是的组件能在发生改变之前从DOM中捕获一些信息(如滚动位置),返回值作为componentDidUpdate的第三个参数;
  5. componentDidUpdate(prevProps, prevState, snapshot) - state或props更新后调用
    33ae2b2a3ebfd7560d78a33f7686251d.jpg

卸载

  • componentWillUnmount() - 组件销毁或卸载时调用;
    9fb18e381ab8e8204fcdd955ebaca1bd.jpg

错误处理

  • static getDerivedStateFromError(callback) - 后代组件跑出错误时调用,并返回一个值以更新state;
  • componentDidCatch(error, info) - 后代组件抛出错误后调用,参数info包含有关组件错误的栈信息;

其它

  • setState();
  • forceUpdate(callback) - 组件强制更新,会跳过shouldComponentUpdate;

示例

import * as React from "react";

export class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 1
};
console.log("1. constructor");
}
static getDerivedStateFromProps(props, state) {
console.log("2. getDerivedStateFromProps");
return {
count: props.count
};
}
componentDidMount() {
console.log("3. componentDidMount");
}
shouldComponentUpdate() {
console.log("4. shouldComponentUpdate");
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log("5. getSnapshotBeforeUpdate");
return null;
}
componentDidUpdate(props, state, snapshot) {
console.log("6. componentDidUpdate");
console.log("snapshot:", snapshot);
}
componentWillUnmount() {
console.log("7. componentWillUnmount");
}
render() {
console.log("0. render");
const { count } = this.state;
return (
<ul>
<li>state: {count}</li>
<li>props: {count}</li>
</ul>
);
}
}
 

完整周期:
8ae37f7af5eb77ec7627ec5a3220286e.jpg

参考

posted @ 2021-02-22 10:51  simple-love  阅读(2469)  评论(0编辑  收藏  举报