react生命周期

挂载阶段

  • constructor() 创建前
  • getDerivedStateFromProps(知道即可)

    static getDerivedStateFromProps(nextProps,prevState) {
    console.log(nextProps, prevState;)
    return nextProps
    //需要加static
    //场景 state的值任何时候都取决于state
    // 必须返回的一个对象或null,且此值不可修改,会和state进行合并
    // 渲染前会执行
    }

  • render() 渲染
  • componentDidMount() 挂载后

    组件渲染完毕执行,一般用来发起ajax请求,添加定时器
    在这里调用setState会触发额外渲染,会导致性能问题,谨慎使用

更新阶段

  • shouldConponentUpdate()

    返回true或者false

  • render()
  • componentDidUpdata()更新后

    组件更新时触发
    接收三个参数:preprops,preState(更新前的state) ,snaoshotValue(快照值)
    这这里也可以发送ajax请求
    使用场景:获取用户信息时,ajax请求,后端返回哈希值,与本地存储的哈希值相同,就不用更新用户信息,否则就需要重新调用用户接口,返回新数据
    使用时需要有条件限制不然就会一直触发(看一下底下的代码)

卸载阶段

  • componentWillUnmount() 卸载前

    离开组件时触发,一般用于清除定时器,变量,取消ajax(离开组件时ajax未请求完毕)

错误边界 getDerivedStateFromError

场景:当子元素数据出错,页面发生报错时,可以用这个方法进行拦截(但是这些报错我们时可以提前规避的,不要依赖这些外力)

  • 在父元素中使用静态方法getDerivedStateFromError(){}进行拦截,返回一个对象
  • 只能在线上环境使用,生产环境不可以
  • 只能处理子组件生命周期里面的错误

componentDidCatch()

生命周期函数,统计错误的次数,反馈给服务器,用于通知编码人员进行bug的解决

小例子

import React, { Component } from 'react';
class View extends Component{

  constructor(props) {
    super(props)
    console.log('constructor执行了')
    this.state = {
      name: '小红',
      age:0
    }
    this.time = null;
  }

  componentDidMount() {
    console.log('componentDidMount执行了')
    this.fn_Time()
  }

  componentDidUpdate(props,preState) {
    console.log('componentDidUpdate执行了')
    //在这里进行判断拦截
    if (this.state.age > 2) {
    clearInterval(this.time)
    }
  }

  fn_Time() {
    this.time=setInterval(() => {
      this.setState((state)=>({age:this.state.age+1}))
    },1000)
  }
  render() {
    console.log('render执行了')
    return (
      <div>
        练习
         {this.state.age}
      </div>
    )
  }
}

export default View

  • 卸载组件
 del = () => {
    ReactDOM.unmountComponentAtNode(document.getElementById("root"))
  }

旧的生命周期

1、初始化阶段:由ReactDOM.render()触发---初次渲染
     1>、constructor()
     2>、componentWillMount()
     3>、render()
     4>、componentDidMount()
2、更新阶段:由组件内部this.setState()或父组件重新render触发
	1>、shouldComponnetUpdate()
	2>、componentWillUpdate()
	3>、render()
	4>、componentDidUpdate()
3、卸载组件:由ReactDom.unmountComponentAtNode()触发
	1>、componentWillUnmount()

新旧生命周期配图

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值