React 生命周期钩子

《React 生命周期钩子》

3个阶段

《React 生命周期钩子》

挂载阶段

  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
《React 生命周期钩子》

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等等,避免内存泄露。

    原文作者:答案在风中飘着
    原文地址: https://segmentfault.com/a/1190000015263074
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞