React 生命周期钩子

图片描述

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()不会引发组件从新渲染。this

3. render

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

4.componentWillMount

组件被挂载到DOM后调用,且只会被掉用一次。在其中调用this.setState()会引发组件从新渲染,组件本次的更新尚未执行完成,又会进入新一轮的更新,致使不断循环更新,进入死循环。
反作用操做,一般用于向后端请求数据。code

更新阶段

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

1.componentWillReceiveProps(nextProps)

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

2.shoudComponentUpdate(nextProps, nextSate)

判断组件是否继续更新,减小没必要要渲染,优化
image对象

3.componentWillUpdate

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

4.componentDidUpadate(prevProps, prevState)

组件更新后调用,能够做为更新后调用DOM的地方,两个参数表明prevProps, prevState,
更新前的属性和状态。图片

卸载阶段

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

相关文章
相关标签/搜索