React生命周期详解

359 阅读3分钟

本文是对于React生命周期的整理,内容是《React工程师修炼指南》中生命周期部分的笔记,只拥有自己的日常复习。

1.生命周期的三个阶段:

React组件的生命周期氛围三个阶段,分别是:

  1. 挂载阶段(Mounting):这个阶段会从组件的初始化开始,一直到创建组件完成并且渲染到真实的Dom中。
  2. 更新阶段(Updating):这个阶段从组件更新开始,一直到组件更新完成并重新渲染到真实的Dom。
  3. 卸载阶段(Unmounting):这个阶段监听组件从Dom中卸载。

2.挂在阶段的生命周期函数

  1. constructor(props):继承自Component的类,不要忘记加super
  2. static getDerivedStateFromProps(从props中获取state🤣): 在挂载阶段可以获取当前的props和state,然后根据props来对state进行修改,使用时注意以下问题:
    1. 内部不能使用this
    2. 这个方法是在React的16.3版本之后才有的
    3. 必须有返回值,返回值是对state的修改,相当于其他地方调用setStatus()时,传入的修改对象。
    4. 组件初始时一定要有state属性
  3. componentWillMount:组件将要挂载
    1. React16.3版本之后不建议再使用,如果在17版本使用需要写成UNSAFE_ComponentWillMount
    2. 不能和getDerivedStateFromProps同时使用
    3. render:根据return中的内容生成虚拟dom,然后提交给ReactDOM,渲染真实DOM。
  4. componentDidMount:组件已经挂载完毕,虚拟的dom已经添加到真实的dom中了。
import React, { Component } from 'react';
class App extends Component {
  constructor(props){
    super(props);
    console.log("1-组件初始化");
    this.state = {
      nba:"科比"
    };
  }
  // 🚀 不能和willMount方法同时使用
  static getDerivedStateFromProps(props,state){
    console.log("2-将props映射到state中");
    return {nba:"艾弗森"} ;
  }
  componentWillMount(){
    console.log("3-组件即将进行挂载");
  }
  render(){
    console.log("4-根据 return 生成虚拟DOM");
    return <h1>hello react</h1>
  }
  componentDidMount(){
    console.log("5-组件已经挂载完毕,虚拟DOM,已经添加到真实的DOM中");
  }
}

export default App;

3.更新阶段的生命周期函数:

更新阶分为3种情况:父组件更新组件本身自己更新forceUpdate

3.1父组件更新:

🚀 16.3之前:

父组件更新引起子组件更新,调用顺序:

componentWillReceiveProps ---> shouldçomponentUpdate ---> componentWillUpdate ---> render ---> comoponentDidUpdate

🚀 16.3:
  • getDerivedStateFromProps方法替代了componentWillReceiveProps;
  • componentWillReceivePropscomponentWillUpdate逐渐被废弃掉
🚀 16.3之后:

getDerivedStateFromProps ---> shouldçomponentUpdate ---> render ---> getSnapshoutBerforUpdate ---> componentDidupdate

  • getSnapshoutBerforUpdate(prevProps,prevState):是在render方法生成虚拟dom之后,渲染真实dom之前,此时的this.propsthis.state是更新后新的propsstate
  • 另外这个方法必须要有返回值,返回值会传递给componentDidUpdate
import React, { Component } from 'react';
class Child extends Component {
  state = {
    name: "child"
  }  
  getSnapshotBeforeUpdate(prevPorps,prevState){
    console.log("4-用于获取更新的 DOM ");
    return {
      info: "要传递给 componentDidUpdate 的信息"
    }
  }
 // 🚀 这个的snapshot就是上面传递过来的{info:"要传递给 componentDidUpdate 的信息"}
  componentDidUpdate(prevPorps,prevState,snapshot){
    console.log("5-组件更细完成",snapshot);
  }
  render(){
    // ...略
  }
}
export default Child;

3.2组件自更新:

组件的自更新主要是调用setStatus方法之后引起的当前组件的更新。也是历经了3个版本的变化:

🚀 16.3之前:

shouldComponentUpdate ---> compoonentWillUpdate --> render ---> componentDidUpdate(这里可以看到组件自己更新已经不再监听props的变化,之监听state的修改)

🚀 16.3:

shouldComponentUpdate ---> render ---> getSnapshotBeforeUpdate ---> componentDidUpdate

🚀 16.4以及之后:

static getDerivedStateFromProps ---> shouldComponentUpdate ---> render ---> getSnapshotBeforeUpdate ---> componentDidUpdate

3.3强制更新:

当依赖的数据不是state或者props时,数据变了希望视图也进行改变,这个时候需要使用forceUpdate