生命周期

1 挂载

1.1 constructor(props)

如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。 在 React 组件挂载之前,会调用它的构造函数。在为 React.Component 子类实现构造函数时,应在其他语句之前前调用 super(props)。否则,this.props 在构造函数中可能会出现未定义的 bug。 在 constructor() 函数中不要调用 setState() 方法。如果你的组件需要使用内部 state,请直接在构造函数中为 this.state 赋值初始 state

  1. constructor(props) {
  2. super(props);
  3. // 不要在这里调用 this.setState()
  4. this.state = { counter: 0 };
  5. this.handleClick = this.handleClick.bind(this);
  6. }

1.2 getDerivedStateFromProps

1.3 render

render()函数应该为纯函数,这意味着在不修改组件 state 的情况下,每次调用时都返回相同的结果,并且它不会直接与浏览器交互。

1.4 componentDidMount()

componentDidMount() 会在组件挂载后(插入 DOM 树中)立即调用。依赖于 DOM 节点的初始化应该放在这里。如需通过网络请求获取数据,此处是实例化请求的好地方。

2 更新

2.1 getDerivedStateFromProps

2.2 shouldComponentUpdate(nextProps,nextState)

2.3 render

2.4 getSnapshotBeforeUpdate

2.5 componentDidUpdate(prevProps, prevState, snapshot)

componentDidUpdate() 会在更新后会被立即调用。首次渲染不会执行此方法。 当组件更新后,可以在此处对 DOM 进行操作。如果你对更新前后的 props 进行了比较,也可以选择在此处进行网络请求。(例如,当 props 未发生变化时,则不会执行网络请求)。

  1. componentDidUpdate(prevProps, prevState, snapshot) {
  2. // 典型用法(不要忘记比较 props):
  3. if (this.props.userID !== prevProps.userID) {
  4. this.fetchData(this.props.userID);
  5. }
  6. }

3 卸载

3.1 componentWillUnmount

4 错误处理

4.1 getDerivedStateFromError

4.2 componentDidCatch

5 补充