Throughout the life of a component, as the props or state of the component changes, its DOM representation changes accordingly.

A component is a state machine that always returns consistent output for a given input.

The life cycle of a React component is divided into three parts: instantiation, lifetime, and destruction time.

ReactIn the application, the component loading sequence and life cycle are shown as follows:

constructor( )

Constructor is ES6’s default method for classes, which is automatically called when an object instance is generated using the new command. Also, the method is mandatory in the class; if no definition is shown, the empty constructor() method is added by default. ⚠️ must manually call the super method when constructor is present. To call this. Props, pass props as shown in the following example:

class MyClass extends React.component{
    constructor(props){
        super(props); The super method must be called to declare constructor
        console.log(this.props); // This.props can be accessed normally}}Copy the code

Constructor is often used to initialize state

class MyClass extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            list: this.props.List }; }}Copy the code

componentWillMount()

Called once globally before the component is mounted. If you can setState in this hook, you can see the updated state after render, it will not trigger repeated rendering. This lifecycle can initiate asynchronous requests and setState. (Discard this life cycle after React V16.3. Set state from Constructor)

render()

Render is the life cycle that the React component must define to render the DOM. ⚠️ do not change state in render, it will trigger an endless loop that will cause stack overflow. Render must return the reactDom.

render() {
	const {nodeResultData: {res} = {}} = this.props;
	if (isEmpty(res)) return noDataInfo;
	const nodeResult = this.getNodeResult(res);
	return (
		<div className="workspace-dialog-result">
			{nodeResult}
		</div>
	);
Copy the code

componentDidMount()

Called after the component has been mounted and only once globally. You can use refs here to get real DOM elements. Asynchronous requests can also be made within the hook, and setState can be made in the asynchronous request.

componentDidMount() {
	axios.get('/auth/getTemplate').then(res => {
		const {TemplateList = []} = res;
		this.setState({TemplateList});
	});
}
Copy the code

componentWillReceiveProps (nextProps )

This lifecycle is triggered when the props changes or the parent component is re-rendered. In this hook, the props parameter nextProps can be obtained, and the previous props can be accessed through this. SetState can be performed during this life cycle. React v16.3 Deprecates this lifecycle and can replace it with static getDerivedStateFromProps.

shouldComponentUpdate(nextProps, nextState)

ShouldComponentUpdate is called after every call to setState to determine if the component needs to be rerendered. The default returns true and requires rerender. Return false and render will not be triggered. In more complex applications, some data changes do not affect the interface display, you can make a judgment here to optimize the rendering efficiency.

componentWillUpdate(nextProps, nextState)

ShouldComponentUpdate returns true or after calling forceUpdate, componentWillUpdate is called. Cannot setState in this hook, it will trigger a repeat loop. (React v16.3 after deprecating the life cycle, you can use the new cycle getSnapshotBeforeUpdate)

componentDidUpdate()

To render a component, call componentDidMount after first render, and call componentDidUpdate after render. The setState in this hook may trigger repeated rendering. You need to judge for yourself, otherwise it will enter an infinite loop.

componentDidUpdate() {
    if(condition) {
        this.setState({.. })/ / set the state
    } else {
        // Stop setting state}}Copy the code

componentWillUnmount()

Called when a component is uninstalled. Normally events registered in componentDidMount need to be deleted here.

Demo

/* Parent component */
import React, { Component } from 'react';
import Header from './components/Header'
import Footer from './components/Footer'
import BodyIndex from './components/BodyIndex'
 
class App extends Component {
  componentWillMount() {
    console.log('App- page about to load ')
  }
 
  componentDidMount() {
    console.log('App- page load completed ')
  }
  render() {
    return (
      <div className="App"> <Header /> <BodyIndex /> <Footer /> </div> ); }}export default App;
Copy the code

Console. log() is also called for componentWillMount and componentDidMount.

/* console.log() contains the following contents and order */App- page is about to load Header- page is about to load body- page is about to load Footer- page is about to load header-page loading complete body- page loading complete Footer- page loading complete App- page loading completeCopy the code

React lifecycle official analysis

  • componentWillMountCalled before rendering, on the client side and on the server side.
  • componentDidMount: called after the first rendering, only on the client side. The component has since been generatedDOMThe structure can be passedthis.getDOMNode()To conduct an interview. If you want to talk to someone elseJavaScriptYou can use this method to call setTimeout, setInterval, or send AJAX requests (to prevent asynchronous operations from blocking the UI).
  • componentWillReceivePropsA new one was received in the componentpropIs called when (after update). This method is initializingrenderIs not called.
  • shouldComponentUpdateReturns a Boolean value. A new one was received in the componentpropsorstateIs called when. When initialized or usedforceUpdateIs not called. This can be used when you are sure that you do not need to update the component.
  • componentWillUpdateA new one was received in the componentpropsorstateBut not yet render when called. Will not be called during initialization.
  • componentDidUpdateCalled immediately after the component finishes updating. Will not be called during initialization.
  • componentWillUnmountIn the component fromDOMIs called immediately when removed from.