React 生命周期钩子

发布时间:2019-06-28 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了React 生命周期钩子脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

图片描述

@H_512_6@3个阶段

image

挂载阶段

  1. constructor
  2. componentWillMount
  3. render
  4. componentDidmount

1. constructor

class SignUpDiaLOG extends React.Component {
  constructor(PRops) {
    suPEr(props);
  }
  render() {}
}

ES6 class构造方法,接收一个props属性对象,props由父组件传入,如果父组件未传入,则指向自身。

通常用于初始化state,以及绑定事件处理方法等工作

2.componentWillMount

组件被挂载到DOM前,只会调用1次, 一般用用更靠前的constructor代替,在其中调用this.setState()不会引起组件重新渲染。

3. render

组件的唯一必要方法,根据组件的propsstate返回一个React元素,用于描述组件的UI
image

4.COMponentWillMount

组件被挂载到DOM后调用,且只会被掉用一次。在其中调用this.setState()会引起组件重新渲染,组件本次的更新还没有执行完成,又会进入新一轮的更新,导致不断循环更新,进入死循环。
副作用操作,通常用于向后端请求数据。

更新阶段

  1. componentWillReceiveProps(nextProps)
  2. shoudComponentUpdate(nextProps, nextSate)
  3. componentWillUpdate
  4. render
  5. componentDidUpadate(prevProps, prevState)

1.componentWillReceiveProps(nextProps)

props变化会触发componentWillReceiveProps,setState()不会触发

React 生命周期钩子

2.shoudComponentUpdate(nextProps, nextSate)

判断组件是否继续更新,减少不必要渲染,优化

React 生命周期钩子

3.componentWillUpdate

在render前调用,作为组件更新前执行某些工作过的地方,(shoudComponentUpdate, componentWillUpdate 不能调用setState()避免引起循环调用)

4.componentDidUpadate(prevProps, prevState)

组件更新后调用,可以作为更新后调用DOM的地方,两个参数代表prevProps, prevState,
更新前的属性和状态。

卸载阶段

组件从DOM中移除的阶段。可用于清楚组件中使用中的定时器,清除componentDidMount手动创建的DOM等等,避免内存泄露

脚本宝典总结

以上是脚本宝典为你收集整理的React 生命周期钩子全部内容,希望文章能够帮你解决React 生命周期钩子所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。