zoukankan      html  css  js  c++  java
  • React从0到1--组件生命周期

    1、React 严格定义了组件的生命周期,生命周期可能会经历如下三个过程
    装载过程( Mount),也就是把组件第一次在 DOM 树中渲染的过程;
    更新过程( Update ),当组件被重新渲染的过程;
    卸载过程( Unmount),组件从 DOM 中删除的过程

    2、装载过程

    我们先来看装载过程,当组件第一次被渲染的时候,依次调用的函数是如下这些:
    constructor
    getlnitialState
    getDefaultProps
    componentWillMount
    render
    componentDidMount

    1. constructor
      
    Es6中创建一个组件的实例,无状态的React组件不需要实例

    1、初始化state

    this.state = {
    count: props.initValue || 0
    }

    2、绑定成员的this环境

    this.onClickIncButton = this.onClickIncButton.bind(this);
    this.onClickDecButton = this.onClickDecButton.bind(this);

    3、getlnitialState 和 getDefaultProps
    React.createClass 方法创造的组件类才会用到这两种方法,分别用来初始化state和props

    4、render
    用于渲染DOM的函数,非常重要


    5、componentWillMount 和 componentDidMount

    //组件装载前
    componentWillMount() {
    console.log ('enter componentWillMount'+ this.props.caption);

    }
    //组件装载后,DOM已经存在,可以使用其他的库,比如JQ来执行其他操作
    componentDidMount() {
    console.log ('enter componentWillMount'+ this.props.caption);

    }

    6、shouldComponentUpdate(nextProps, nextState)
    shouldComponentUpdate决定了一个组件什么时候不需要渲染,必须有返回值,true是渲染,false是不渲染

    shouldComponentUpdate(nextProps, nextState){
    console.log(nextProps, nextState)

    console.log(this.state)
    return (nextProps.caption!==this.props.caption)||(nextState.count!==this.state.count)


    }
    7、componentWillUnmount 
    用于卸载组件












  • 相关阅读:
    jquery.FixedColumns 滚动兼容问题
    面向对象三大特性:继承、封装、多态
    jquery.chosen.js和select2使用笔记
    Git查看、删除、重命名远程分支和tag(转载)
    GIT忽略追踪文件
    git代码量统计(转载)
    SQL SERVER如何收缩日志-通过脚本收缩(转发)
    GIT常用命令
    解决 git extensions 每次提交需要输入用户名和密码
    Mysql 5.7初始化密码
  • 原文地址:https://www.cnblogs.com/lk1186578324/p/9803707.html
Copyright © 2011-2022 走看看