Skip to content

生命周期

生命周期

组件从创建到被销毁的过程称为组件的生命周期。通常,有以下三个阶段:

挂载阶段

  • constructor

  • componentWillMount 用得较少,因为此阶段的都可移到 constructor 里,该方法调用 this.setState 不会引起重渲

  • render 根据组件的 props 和 state 返回一个 React 元素。需注意,render 并不负责组件的实际渲染,它只是返回一个 UI 描述,真正渲染 DOM 由 React 本身负责,该阶段不能执行有副作用的操作

  • componentDidMount 组件被挂载后只调用一次,依赖 DOM 节点操作可放该阶段中,还有服务端请求等操作,this.setState 会引起重渲

更新阶段

  • componentWillReceiveProps(nextProps) 引起组件更新过程调用。state 引起组件更新不会触发该方法的执行。nextProps 是父组件传递给当前组件的新 props. 因此往往需比较 nextProps 和 this.props 来决定是否执行 props 发生变化后的逻辑

(1)在 componentWillReceiveProps 中调用 setState,只有在组件 render 及其之后的方法中,this.setState 指向的才是更新后的 state。在 render 之前的方法 shouldComponentUpdate、componentWillUpdate 中,this.setState 依然指向的是更新前的 state

(2)通过调用 setState 更新组件状态并不会触发 componentWillReceiveProps 的调用,否则会进入一个死循环 componentWillReceiveProps -> this.setState -> componentWillReceiveProps ...

  • shouldComponentUpdate(nextProps, nextState) 该方法决定组件是否继续执行更新过程。当方法返回 true 时(默认),组件会继续更新过程。当返回 false,组件的更新过程停止,后续的 componentWillUpdate、render、componentDidUpdate 也不会被调用,这是优化性能的一个重要钩子

  • componentWillUpdate(nextProps, nextState) 在组件 render 前调用,可作为组件更新前执行某些工作的地方

shouldComponentUpdate 和 componentWillUpdate 中都不能调用 setState,否则会引起循环调用问题

  • render 同上,省略了

  • componentDidUpdate(prevProps, prevState) 组件更新后被调用,可作为更新后操作 DOM 的地方,其参数 prevProps, prevState 代表组件更新前的 props 和 state

卸载阶段

组件从 DOM 中被卸载的过程,只有一个声明周期方法

  • componentWillUnmount 在组件卸载前调用,可在这里执行一些清理工作。如定时器或手动创建的 DOM 元素等,以避免内存泄漏

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

共 20 个模块,1301 篇 Markdown 文档。