In addition to the mount phase, there is also an “update phase.” Specifically, setState causes React. Js to re-render the component and apply the component changes to the DOM element. This is a component change process. React.js also provides a series of lifecycle functions that allow you to perform operations during component updates.

  1. shouldComponentUpdate(nextProps, nextState)You can use this method to control whether or not components are rerendered. If the returnfalseComponents are not re-rendered. This lifecycle is useful for react.js performance optimization.
  2. componentWillReceiveProps(nextProps)The: component receives a new one from the parentpropsCall before.
  3. componentWillUpdate(): called before the component begins rerendering.
  4. componentDidUpdate()Called after the component rerenders and changes to the real DOM.

 

<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8" />
<title>React lifecycle</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Clock extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      date: new Date()
    }
  }
  componentWillMount () {
    setTimeout(() = > {
      this.setState({ date: new Date()})},1000)
  }
  componentWillReceiveProps () {
    console.log('componentWillReceiveProps');
  }
  shouldComponentUpdate () {
    console.log('shouldComponentUpdate');
    return true;
  }
  componentWillUpdate () {
    console.log('componentWillUpdate');
  }
  componentDidUpdate () {
    console.log('componentDidUpdate');
  }
  render () {
    const name = this.props.myName;
    return (
      <div>
        <h1>
          <p>{name}, the current time is</p>
          {this.state.date.toLocaleTimeString()}
        </h1>
      </div>)}}class Index extends React.Component {
  constructor () {
    super(a);this.state = {
      name: 'xu'
    }
  }
  componentWillMount () {
    setTimeout(() = > {
      this.setState({ name: 'tongbao'})},2000)
  }  
  render () {
    return (
      <div>
        <Clock myName={this.state.name}/>
      </div>
    )
  }
}
ReactDOM.render(
  <Index />.document.getElementById('root'));</script>
</body>
</html>
Copy the code