当前位置:   article > 正文

React生命周期_componentdidmount和render

componentdidmount和render

React生命周期

钩子函数执行顺序 constructor => render =>componentDidMount
在这里插入图片描述

挂载时(constructor->render->componentDidMount)
  • constructor在创建组件时最先执行,常用于初始化state为事件处理程序绑定this
  • render每次组件渲染都会去执行,不管是初次渲染还是多次渲染都会触发,说白了就是渲染UI(注意在render里面不能使用setstate)不然就会报错不能在状态变化的时候进行更新 导致出这种错的原因是在使用setState的时候我们就会去触发render,而你在render里面去调用setState就会进行死循环
  • componentDidMount组件挂载(完成DOM渲染)在这里我们可以进行DOM操作(发送网络请求,DOM操作)
更新时
  • render 触发render 有三种情况
  • 1.new props 接收到新属性的时候(例如在接收父组件的数据属性时)

  • 2.setState 修改数据的时候

  • 3.forceUpdate 调用render这个方法的时候(强制更新)

sum = () => {
    // this.setState({
    //   num: this.state.num + 1
    // })
    this.forceUpdate()//强制刷新
    console.log(this.state.num);
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
更新阶段的钩子函数(render->componentDidUpdate)

先执行render 然后再去执行componentDidUpdate

  • render
  • componentDidUpdate触发时机是在组件更新完成并在DOM渲染完成之后再去触发的 ,作用是发送网络请求,跟DOM操作 注意:如果要使用setState 必须放在if的条件中,如果直接调用setState也会去递归更新报错,

报错流程(事件触发更新状态setState->render->componentDidUpdate->setState->render…)所以要么在componentDidUpdate写个条件

  componentDidUpdate(prevProps,curprops) {
    console.warn('生命周期钩子函数:componentDidUpdate');
    console.log('第一次从父组件接收过来:',prevProps,'前一次的子组件就是当前组件内部的数据',curprops,'更新后的数据',this.state);
     //要想在componentDidUpdate中使用setState修改必须让加条件,条件就是前后两次修改数据不一样
    if(curProps.count!==this.state.count){ //如果是修改父元素的数据就比较第一个参数
    	this.setState({})//这样就不会出现递归更新
    }
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
卸载时(componentWillUnmount)

卸载阶段,页面关闭,或者组件卸载,执行清理工作(比如:清除定时器,清除cookie等关键数据)

react避免不必要的重新渲染(shouldComponentUpdate)

借助钩子函数shouldComponentUpdate ->render

class Hello extends Component{

  shouldComponentUpdate(nextProps,nextState){
    console.log('nextProps',nextProps); //现在的props
    console.log('props',this.props);//之前的props
    console.log('nextState',nextState);//现在的state
    console.log('state',this.state);//之前的state
    return true  //如果返回false那么状态改变将不会去渲染,一般最终是判定前一个值跟后面一个值是否是一样的
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

以上都是目前常见的一些钩子函数 不常用的见以下不常用钩子函数

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/857459
推荐阅读
相关标签
  

闽ICP备14008679号