React15 Lifecycle

127 阅读2分钟

组件初始化

调用生命周期中的render方法生成虚拟DOM,然后调用ReactDOM.render方法生成真实DOM

组件更新

再次调用render方法生成新的虚拟DOM,通过diff算法定位出两次虚拟DOM的差异,从而针对发生变化的真实DOM作定向更新

React15 LifeCycle

constructor()
componentWillReceiveProps()
shouldComponentUpdate()
componentWillMount()
componentWillUpdate()
componentDidUpdate()
comopnentDidMount()
render()
componentWillUnmount()

挂载阶段:组件的初始化渲染

constructor()
componentWillMount()
render()
componentDidMount()

以下三个生命周期函数在挂载阶段仅触发一次

constructor()
componentWillMount()
componentDidMount() 

render方法在执行过程中并不会去操作真实DOM,它的职能是把需要渲染的内容返回出来。

真实DOM的渲染工作在挂载阶段是由ReactDOM.render方法来承接的。

componentDidMount方法在渲染结束后被触发,此刻真实DOM已经挂载到了页面上,可以在这个生命周期函数中执行真实DOM的相关操作,异步请求也可以放在此生命周期中来做。

更新阶段:组件的更新

componentWillReceiveProps()	由父组件触发
shouldComponentUpdate()		可由组件自身触发
componentWillUpdate()
render()
componentDidUpdate()

componentWillReceiveProps(nextProps)

Note that if a parent component causes your component to re-render,
this method will be called even if props have not changed. 
Make sure to compare the current and next values if you only want to handle changes.

引用自Reactjs official

大意是指如果父组件导致组件重新渲染,即使props没有发生改变也会调用该方法

import React from "react";
import Son from "../Son";
export default class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 1,
      passCount: 1
    };
  }
  toggle() {
    this.setState({
      count: this.state.count + 1
    });
  }
  passToggle() {
    this.setState({
      passCount: this.state.passCount + 1
    });
  }
  render() {
    const { count, passCount } = this.state;
    return (
      <div>
        <h2>Parent Component</h2>
        <h2>status: {count}</h2>
        <button onClick={() => this.toggle()}>click</button>
        <button onClick={() => this.passToggle()}>pass click</button>
        <Son passCount={passCount} />
      </div>
    );
  }
}
import React from "react";

export default class Son extends React.Component {
  constructor(props) {
    super(props);
  }
  componentWillReceiveProps(nextProps) {
    console.log("componentWillReceiveProps", nextProps, this.props.passCount);
  }
  render() {
    return (
      <div>
        <h2>Son Component</h2>
        <h2>{this.props.passCount}</h2>
      </div>
    );
  }
}

打开控制台,调用toggle方法后,发现父组件的状态发生变化,子组件componentWillReceiveProps生命周期函数也会被调用

stackblitz demo

shouldComponentUpdate(nextProps, nextState)

React组件会根据shouldComponentUpdate的返回值来决定是否执行该方法之后的生命周期,进而决定是否对组件进行re-render

componentDidUpdate

该生命周期函数在组件更新完之后被触发,componentDidUpdate的执行作为子组件更新完毕的标志通知到父组件

卸载阶段:组件的卸载

componentWillUnmount()