Life cycle before React16

Prior to Act16, the lifecycle was actually divided into four phases: component initialization, component mount, component update, and component unload.

Component initialization phase

constructor

The constructor() method in the component at this stage accepts props receives props passed down from the parent component. You can also define the initial content of this.state within constructor(). Note: If you write the constructor method inside the component, you must use super() inside and call super(props) before any other statements. Otherwise, this. Props might have undefined bugs in the constructor.

 constructor(props) {
  super(props)
  console.log(this.props) // Internally, props can be used
  this.state = {
    // Define the initial value of state}}Copy the code

Component mount phase

componentWillMount

Called just before the component is about to be mounted to the DOM, it is only called once, and changing the value of state in this method does not cause the component to re-render. (It is not recommended to write asynchronous operations, such as data requests, in this method because asynchronous operations may block the UI.)

componentWillMount(){}
Copy the code

render()

This function creates a virtual DOM that represents the output of the component. Data can only be accessed through this.props and this.state, and this. Render can return NULL, false, or any React component, only one top-level component can appear, not a set of elements (improved in Act16 to return a set of elements or a single string).

Render(){
	return (
  		/ / the react components)}Copy the code

componentDidMount

Called after the component is mounted to the Dom and only once. At this point, the component has generated the corresponding DOM structure, and the real DOM can be accessed in this function either through reactdom.finddomNode () or through the this.refs.[refName] property. (It is recommended to write asynchronous operations such as data requests in this method.)

componentDidMount() {
  // Make asynchronous data requests or get dom
}
Copy the code

Component update phase

componentWillReceiveProps

This function takes a parameter, nextProps, which is called when the parent component retransmits props. Get the new props and compare the old props to see if there is any change. If there is any change, update the state with this.setState. You can also update the state without comparing the old and new props values.

componentWillReceiveProps(nextProps) {
  / / sample
  if(nextProps.state ! = =this.props.state) {
     this.setState({
       state: nextProps.state }); }}Copy the code

Tip: official componentWillReceiveProps invokes the enclosing setState () will not cause the second rendering.

Since each child components to receive new props, to render time, unless you use shouldComponentUpdate to stop rendering again, but you can be updated as new props componentWillReceiveProps state, While updating state also triggers a rerender, it does not trigger additional render.

shouldComponentUpdate(nextProps,nextState)

This function is the only one that can control the life cycle of a component’s rendering. If the props and state changes do not require the component to be re-rendered. You can return false in this function to prevent the component from being rerendered. To optimize component performance and reduce unnecessary rendering of components.

shouldComponentUpdate(nextProps, nextState){
  // return true Updates the component
  // return false does not update the component
}
Copy the code

componentWillUpdate(nextProps,nextState)

ShouldComponentUpdate returns true, call this function just before the component is about to rerender (don’t update props or state in it, cause the component to go into an infinite loop), and then call the Render method to rerender.

componentWillUpdate(nextProps,nextState) {
  // Do not update props or state here
}
Copy the code

componentDidUpdate(prevProps,prevState)

This method is called after the component has been re-rendered to get the props and state before the update. This function is called every render except for componentDidMount, which is called the first time. Similar to componentDidMount, you can manipulate the updated DOM here.

componentDidUpdate(prevProps,prevState) {}
Copy the code

Component uninstallation phase

componentWillUnmount

This function is called before the component is unloaded to perform some cleanup, such as cleaning up timers or event listeners used in the component to avoid causing a memory leak.

componentWillUnmount() {
  // Clear timer or event listener
}
Copy the code

The lifecycle of React16

The lifecycle of Act16 introduces three new lifecycle functions: getDerivedStateFromProps, getSnapshotBeforeUpdate, and componentDidCatch. Deprecated three lifecycle functions: getDerivedStateFromProps, getSnapshotBeforeUpdate, and componentDidCatch. ComponentWillMount, componentWillReceivePorps componentWillUpdate. The other lifecycle functions are the same as described earlier.

getDerivedStateFromProps(props, state)

This function is called during the component mount phase and subsequent update phase. It calculates the expected state change according to the props and state parameters and returns an object representing the new state for update. If no update is required, return NULL. This function is used to replace componentWillReceiveProps.

static getDerivedStateFromProps(props, state) {
  // Calculate the expected state changes based on props and state, and the returned result is sent to setState
}
Copy the code

getSnapshotBeforeUpdate(prevProps, prevState)

This function is called after render, when the DOM can be read but cannot be used. It enables the component to capture some information (for example, scroll position) from the DOM before changes are made. The return value is taken as the third argument to componentDidUpdate. This function works with componentDidUpdate and can replace componentWillUpdate.

  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log('getSnapshotBeforeUpdate');
    return 'react16';
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('snapshot = ', snapshot);
  }
Copy the code

static getDerivedStateFromError()

This life cycle is invoked after a descendant component throws an error. It takes the thrown error as an argument and returns a value to update state.

Static getDerivedStateFromError(error) {// Update state so that the UI can be degraded in the next renderingreturn { hasError: true };
  }
Copy the code

ComponentDidCatch (error, the info)

Javascript anywhere triggers this function.

ComponentDidCatch (error, info) {Copy the code

conclusion

The updated life cycle of Act16 can be summarized as follows:

Component mount phase
  • constructor
  • getDerivedStateFromProps
  • render
  • componentDidMount
Component update phase
Component uninstallation phase
  • componentWillUnmount

  • Images from the projects. Wojtekmaj. Pl/react – lifec…

Reference links: