深入了解React组件重新渲染的条件和生命周期

原文链接: https://www.mk2048.com/blog/blog.php?id=h0jbc1kh0jaa&title=%E6%B7%B1%E5%85%A5%E4%BA%86%E8%A7%A3React%E7%BB%84%E4%BB%B6%E9%87%8D%E6%96%B0%E6%B8%B2%E6%9F%93%E7%9A%84%E6%9D%A1%E4%BB%B6%E5%92%8C%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F

React组件rerender的真正条件

  1. 当前组件的State中的属性改变时且当前组件的shouldcomponentupdate返回true,那么当前组件会rerender

  2. 组件的props中的任一属性的值有变化(即使这个任一属性的值是对象,变化的仅仅是该对象中的某属性的值,此刻也算props发生了变化)且当前组件的shouldcomponentupdate return true时且当期组件所有父级以上组件的shouldcomponentupdate return true,当前组件才会re-render

  3. 当前组件的shouldcomponentupdate即使返回false,当前组件里子组件若满足1中的条件,这个子组件依然会重新渲染

各个生命周期的深层含义

shouldComponentUpdate

触发时机1:

when new props(当props中某属性的值为对象时,该对象中某属性值发生了变化,也会触发该函数的调用) are being received且所有父级组件的shouldComponentUpdate得返回true当前组件才会触发该回调

触发时机2:

即使所有父级组件的shouldComponentUpdate返回false,当前组件的state有变化,当前组件的该回调依然会触发

默认值

Defaults to true. This method is not called for the initial render or when forceUpdate() is used

其他情况

if shouldComponentUpdate() returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked

componentWillReceiveProps

触发时机1:

当当前组件的props某属性有变化时(包括这种情况:当props中某属性的值为对象时,该对象中某属性值发生了变化)且所有父级以上组件的shouldComponentUpdate返回true(当前组件的shouldComponentUpdate是否返回true不重要)时当前组件的该回调才会触发调用

触发时机2:

即使当前组件的shouldComponentUpdate return false且当前组件没有props的更新,父级组件re-render了,当前组件该函数还是会触发调用

组件第一次渲染完成:mounting

mouting含义

whenever the Clock is rendered to the DOM for the first time. This is called "mounting" in React

在组件内相应回调函数叫componentDidMount() componentWillMount

组件被销毁时:Unmounting

whenever the DOM produced by the Clock is removed. This is called "unmounting" in React

在组件内相应回调函数叫componentWillUnmount()

组件正在被重新渲染: Updating

在组件内相应回调函数叫componentWillUpdate componentDidUpdate


更多专业前端知识,请上 【猿2048】www.mk2048.com

猜你喜欢

转载自blog.csdn.net/weixin_39037804/article/details/102749384
今日推荐