zoukankan      html  css  js  c++  java
  • react 生命周期

    生命周期

    某个事件(事务)成立时候触发的函数

    一个组件完整的生命周期包含实例化阶段、更新活动阶段、销毁阶段三个阶段

    前夕

    组件初始化(initialization)

    也就是代码中类的构造方法constructor(),APP继承了react Component这个基类,才能有render()、生命周期等方法可以使用

    class App extends React.Component{//App这个类继承了react的组件
        //constructor只执行一次
        constructor(props){//props是父级传过来的
            super(props)
           /*
           状态初始化必须放在constructor里面
           没有super就拿不到this
           只要更新state就会更新视图
           */
            this.state = {//自己的数据
                num:0
            }
        }

    其中super(props)

    //1、用来调用基类的构造方法( constructor() )
    //2、将父组件的props注入给子组件

    constructor()

    //用来做一些组件的初始化工作,
    //如定义this.state的初始内容
     
    组件挂载(Mounting)阶段

    只会执行一次

    constructor

    //数据初始化

    componentWillMount 

    在组件挂载到DOM前调用

    //ComponentWillMount方法调用在constructor之后 render之前,该方法调用setState方法不会触发重新渲染。所以他一般不会用作加载数据,用的较少

    render 解析JSX

    //根据组件的props和state
    //return一个React元素(描述组件,即UI)
    //不负责组件实际渲染工作

    componentDidMount 

    组件挂载到DOM后调用

    //多用于数据请求
     
    组件更新(Update)阶段

    componentWillReceiveProps(nextProps) 

    当父级数据发生变化

    //此方法只调用于props引起的组件更新过程中
    //参数nextProps是父组件传给当前组件的新props
    //父组件render方法的调用不能保证重传给当前组件的props是有变化的
    //所以根据nextProps和this.props来查明重传的props是否改变,以及如果改变了要执行啥
    //比如根据新的props调用this.setState出发当前组件的重新render

    shouldComponentUpdate(nextProps,nextState) 

    组件是否需要更新,默认返回true

    //此方法通过比较nextProps,nextState以及当前组件的this.props,this.state
    //返回true,则当前组件将继续执行更新过程
    //返回false,则当前组件停止更新
    //以此可用来减少组件的不必要渲染,优化组件性能

    componentWillUpdate(nextProps,nextState)

    组件更新前调用

    render

    重新调用(相当于vue中computed)

    componentDidUpdate(prevProps,prevState)

    组件更新后调用

    //可以操作组件更新的DOM
    //prevProps和prevState这两个参数指的是组件更新前的props和state

    卸载阶段 unmounting

    此阶段只有一个生命周期方法 componentWillUnmount

    组件卸载时候调用

    //可以用来清除定时器、清除各种事件
    //清除componentDidMount中手动创建的DOM元素等(以避免引起内存泄漏)
  • 相关阅读:
    Java 单测 回滚
    Java四种线程池的使用
    git gc
    Git 常用命令
    JPA 批量新增
    SpringData JPA 排除 扫描 exclude-filter 不能使用解决
    开源许可证GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
    深入浅出 RPC
    阿里 Java面试 知识点
    Eclipse Egit 安装
  • 原文地址:https://www.cnblogs.com/theblogs/p/10295864.html
Copyright © 2011-2022 走看看