React component (life cycle)

Time:2021-2-11

The life cycle of RN component is as follows:

 

Lifecycle callback function

mount

When a component instance is created and inserted into the DOM, its life cycle call order is as follows:

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

be careful:

The following lifecycle methods are going to be obsolete and should be avoided in New Code:

  • UNSAFE_componentWillMount()

to update

When the props or state of a component changes, an update is triggered. The call order of component update life cycle is as follows:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

be careful:

The following methods are going to be obsolete and should be avoided in New Code:

  • UNSAFE_componentWillUpdate()
  • UNSAFE_componentWillReceiveProps()

uninstall

When a component is removed from the DOM, the following methods are called:

  • componentWillUnmount()

error handling

When an error is thrown in the render process, lifecycle, or the constructor of a subcomponent, the following methods are called:

  • static getDerivedStateFromError()
  • componentDidCatch()

 

Common life cycle methods

1、render()

render()Method is the only method that must be implemented in a class component.

WhenrenderWhen called, it checksthis.propsAndthis.stateAnd returns one of the following types:

  • The react element. Usually created through JSX. For example,It will be rendered as DOM node by react,Will be rendered as a custom component by react, regardless ofOrAll are react elements.
  • Array or fragments. Enables the render method to return multiple elements..
  • Portals。 You can render child nodes into different DOM subtrees.
  • String or numeric type. They are rendered as text nodes in the dom
  • Boolean type ornull. Nothing is rendered. (mainly used to support return)test &&Where test is Boolean. )

render()The function should be a pure function, which means that it will return the same result every time it is called without modifying the component state, and it will not directly interact with the browser.

To interact with the browser, please clickcomponentDidMount()Or other lifecycle methods. Keeprender()It’s a pure function that makes components easier to think about.

be careful

IfshouldComponentUpdate()If false is returned, therender()

2、constructor()

If state is not initialized or method binding is not performed, there is no need to implement a constructor for the react component.

Before the react component is mounted, its constructor is called. In for React.Component When a subclass implements a constructor, it should be called before other statements.super(props). Otherwise,this.propsUndefined bugs may appear in constructors.

Generally, in react, constructors are only used in the following two cases:

  • By givingthis.stateObject to initialize the internal state.
  • Bind instance for event handler

Inconstructor()Do not callsetState()Methods. If your component needs to use internal state, pleaseDirectly in the constructor forthis.stateAssign the initial state.

Avoid introducing any side effects or subscriptions into the constructor. If you encounter this scene, please place the corresponding operation in thecomponentDidMountMedium

 

3、componentDidMount()

componentDidMount()Will be called immediately after the component is mounted (inserted into the DOM tree).Initialization that depends on DOM nodes should be placed here. If you need to obtain data through network request, this is a good place to instantiate the request

This method is more suitable for adding subscriptions. If you add a subscription, don’t forget tocomponentWillUnmount()Unsubscribe in

youCan be incomponentDidMount()Call directly fromsetState(). It triggers additional rendering, but this rendering occurs before the browser updates the screen. This ensures that even in therender()In the case of two calls, the user will not see the intermediate state. Use this pattern with caution as it can cause performance problems. Usually, you should be in theconstructor()Initialize state in. If your rendering depends on the size or location of DOM nodes, such as modals and tools, you can use this method

 

4、componentDidUpdate()

componentDidUpdate()Will be called immediately after the update. The first rendering does not perform this method.

When the component is updated, you can operate on the DOM here. If you compare the props before and after the update, you can also choose to make a network request here.

componentDidUpdate(prevProps) {
  //Typical usage (don't forget to compare props)
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

 

You tooCan be incomponentDidUpdate()Call directly insetState()But pay attention to itMust be wrapped in a conditional statement, as in the example above, otherwise it will lead to a dead loop. It also causes additional re rendering, which is invisible to the user, but affects component performance.Instead of “mirroring” props to state, consider using props directly

 

5、componentWillUnmount()

componentWillUnmount()It is called directly before the component is unloaded and destroyed. In this method, necessary cleanup operations are performed, such as clearing timer, canceling network request, or clearing time incomponentDidMount()And so on.

componentWillUnmount()MediumShould not callsetState(), because the component will never be re rendered. After the component instance is unloaded, it will never be mounted again.

 

Less commonly used life cycle methods

Not very often. They are convenient occasionally, but in most cases components may not need them.

 

1、shouldComponentUpdate()

According toshouldComponentUpdate()To determine whether the output of react component is affected by the change of current state or props. The default behavior is state, and the component re renders every time it changes.

 

2、static getDerivedStateFromProps()

getDerivedStateFromPropsIt will be called before calling the render method, and will be invoked at the initial mount and subsequent updates. It should return an object to update the state, and if it returns null, nothing will be updated.

This method applies to the value of state, which depends on props at any time.

Derived states can lead to code redundancy and make components difficult to maintain. Make sure you are familiar with these simple alternatives:

  • If you need to perform side effects (such as data extraction or animation) in response to changes in props, usecomponentDidUpdate
  • If you only want to recalculate some data when the? Prop changes, use the memory helper instead.
  • If you want to “reset” some states when the prop changes, consider making the component completely controlled or usedkeyMake the component completely out of control.

3、getSnapshotBeforeUpdate()

getSnapshotBeforeUpdate()Invoked before the last render output (submitted to the DOM node). It enables the component to capture some information (for example, scroll position) from the DOM before a change occurs. Any return value of this lifecycle is passed as a parameter to thecomponentDidUpdate()

This usage is not common, but it may appear in UI processing, such as chat threads that need to handle scrolling positions in a special way.

The value of snapshot (ornull)。

 

Error boundaries

Error boundaries is a react component. It will catch JavaScript errors anywhere in its subcomponent tree, record these errors, and display the degraded UI instead of the collapsed component tree. The error boundaries component captures errors that occur in the life cycle method and its entire tree constructor during rendering.

If the class component defines a lifecycle methodstatic getDerivedStateFromError()OrcomponentDidCatch()Either (or both) of the two, it becomes error boundaries. By updating the state through the lifecycle, components can catch the unhandled JavaScript errors in the tree and display the degraded UI.

Situations where only error boundaries components are used to recover from unexpected exceptions; do not use them for process control.

For more details, seeError handling in react 16

be careful

Error boundaries captures only errors in the following components in the component tree. But its own errors cannot be caught.