React 生命周期

React 生命周期

只有 class 组件有生命周期方法,函数组件没有生命周期方法。

生命周期过程

  • 挂载卸载过程
constructor
componentWillMount
componentDidMount
componentWillUnmount
  • 更新过程
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
render

常用生命周期方法

  • constructor()
    1. 完成 React 数据的初始化,即创建组件时初始化 state;
    2. 该方法接收两个参数:propscontext
    3. 该方法中若要获取到props,就必须要在constructor()super()的参数里写上props,即constructor(props){super(props);}
    4. 注意:只要使用了constructor()就必须写super(),否则会导致 this 指向错误。
  • componentDidMount()
    1. 组件第一次渲染完成,此时 dom 节点已经生成,可以在这里进行网络请求或其他操作,且调用 setState 方法后会重新渲染。
  • componentWillUnmount()
    1. 完成组件的卸载和数据的销毁:clear你在组建中所有的setTimeout,setInterval,使用removeEventListener()移除组件中所有的监听。
  • render()
    1. render()会插入 jsx 生成的 dom 结构,React 会生成虚拟 dom 树,在每一次组件更新时 React 会比较更新前后的新旧 DOM 树,找到最小的有差异的 DOM 节点重新渲染;
    2. 在不同的地方使用setState()修改state里面的值,都会触发render()生命周期方法;
    3. 注意:别在render()方法里面使用setState(),因为每次渲染时都会触发setState()
import React, {
      Component } from 'react';

// 常用生命周期方法
class LifeCycle extends Component {
     
  // 完成 React数据 的初始化
  constructor(props) {
     
    super(props);
    console.log('构造函数,constructor');
  }
  // dom渲染完成 可以进行网络请求 或者 其他操作
  componentDidMount() {
     
    console.log('dom渲染完成,componentDidMount');
  }
  // 完成组件的卸载和数据的销毁
  componentWillUnmount() {
     
    console.log('组件的卸载和数据的销毁,componentWillUnmount');
  }
  // 每次渲染触发
  render() {
     
    console.log('渲染触发,render');
    return <></>;
  }
}

export default LifeCycle;

你可能感兴趣的:(React,react,生命周期,render,js)