Live2D

vue 和 react 生命周期的总结

好久没写博客了,今天抽点时间总结解一下大雷讲的有关生命周期的知识点:

vue生命周期(钩子函数):

  1. beforeCreate(){}--->2.Create--->3.beforeMount---->4.mounted --->5.beforeUpdate--->6updated---->7.beforeDestroy ---->8.destoryed

 

常用的举例说明:

beforeCreate(){

           //this.say()//这里会报错  this没有

        },

        created(){ //这里可以使用this  数据请求

            this.username="leson";

        },

        beforeMount(){//页面结构加载完成以前

 

        },

        mounted(){//页面结构完成

            //写dom操作  定时器 

            //事件  window.onscroll      

       },      

        updated(){

            console.log(this.userage);

        },

 

 react中的生命周期:

constructor(props) {

    //接收父组件传来的数据

    //声明当前组件 自己的数据

    super(props);

    this.state = {

      num: 10,

    };

    console.log("初始化1"); //页面最开始加载时

  }

 

  componentDidMount() {

    //页面加载完成以后的数据请求

    console.log("页面结构加载完成");

  }

 

  componentDidUpdate() {

    //componentDidUpdate 数据修改完毕的时候

    console.log("更新完毕");

  }

  componentWillUnmount() {

    //componentWillUnmount 离开页面的时候

    console.log("销毁");

  }

  shouldComponentUpdate(nextProps, nextState) {

    //console.log(nextState); 控制数据修改后,页面是否渲染

    if (nextState.num % 2 == 0) {

      return true;

    }

    return false;

  }

  getSnapshotBeforeUpdate(prevProps, prevState) {

    //   getSnapshotBeforeUpdate 记录数据更改前的上一次数据   --缓存作用

    console.log(prevState.num);

    return null;

  }

  render() {

    //横跨两个生命周期 渲染页面

    console.log("开始渲染页面2");

 

    return (

      <div>

        生命周期{this.state.num}

        <button

          onClick={() => {

            this.setState({

              num: this.state.num + 1,

            });

          }}

        >

          +

        </button>

      </div>

    );

  }

 

posted @ 2021-03-02 14:28  喻佳文  阅读(161)  评论(0编辑  收藏  举报