React 基础_生命周期

组件的生命周期#

挂载阶段#

组件被创建,执行初始化,并被挂载到 DOM 中,完成组件的第一次渲染,依次调用的生命周期方法:

  1. constructor
  2. componentWillMount
  3. render
  4. componentDidMount
1.constructor#

组件被创建时,首先调用组件的构造方法,接收一个 props 参数,props 是从父组件中传入的属性对象,如果父组件中没有没有传入属性而组件自身定义了默认属性那么这个 props 指向的就是组件的默认属性。调用 super (props) 才能保证 props 被传入组件中。constructor 通常用于初始化组件的 state 以及绑定事件处理方法等工作

2.componentWillMount#

在组件被挂载到 DOM 前调用,且只会被调用一次。在实际项目中很少用到。调用 this.setState 不会引起组件的重新渲染

3.render#

定义组件时唯一必要的方法根据组件的 props 和 state 返回一个 React 元素,用于描述组件的 UI,通常 React 元素使用 JSX 语法定义。不能再 render 中调用 this.setState,这会改变组件的状态

4. componentDidMount#

再组件被挂载到 DOM 后调用,且只会被调用一次。这时候已经可以获取到 DOM 结构,因此依赖 DOM 节点的操作可以放到这个方法中。这个方法通常还会用于向服务器请求数据。在这个方法中调用 this.setState 会引起组件的重新渲染

更新阶段#

  1. componentWillReceiveProps
  2. shouldComponentUpdate
  3. componentWillUpdate
  4. render
  5. componentDidUpdate
1.componentWillReceiveProps(nextProps)#

这个方法旨在 props 引起的组件跟新过程中,才会被调用
参数 nextProps 是父组件传递给当前组件的新 props
nextProps 方法的值可能和子组件当前 props 的值相等,因此比较 nextProps 和 this.props 来决定是否执行 props 发生变化后的逻辑,比如根据新的 props 调用 this.setState 触发组件的重新渲染

2.shouldComponentUpdate(nextProps,nextState)#

这个方法决定组件是否继续执行更新过程
通过比较 nextProps,nextState 和组件当前的 props,state 决定这个方法的返回结果

3.componentWillUpdate(nextProps,nextState)#

这个方法在组件 render 调用前执行,一般很少用到

4.componentDidUpdate(prevProps,prevState)#

组件更新后被调用,可以作为操作更新后的 DOM 的地方。参数 prevProps,prevState 代表组件更新前的 props 和 state

卸载阶段#

  • componentWillUnmount
    这个方法在组件被卸载前调用,可以在这里执行一些清理工作,比如清除组件中使用的定时器,清除 componentDidMount 中手动创建的 DOM 元素,避免引起内存泄漏

只有类组件才具有生命周期方法,函数组件是没有生命周期方法的

本作品采用《CC 协议》,转载必须注明作者和本文链接