Come and join us!
“The Newbies of Little Wo Shan” provides front-end developers with technical information and a series of basic articles. For a better user experience, please go to xhs-rookies.com/ to learn the latest articles.
“Code Tailor “, if you are interested in our article, or would like to make some suggestions, please follow the official account of “Rookie of Xiaohe Mountain” on wechat and contact us. You can also view our article on wechat. Every suggestion or approval is a great encouragement to us!
preface
In this section, we introduce the life cycle of React components and the declarative cycle functions associated with the life cycle.
** Note: ** The React lifecycle is in version 17.0.1 and may change
This article introduces you to the following:
- Know the life cycle
- Life cycle analysis
- Commonly used life cycle functions
- Life cycles are not commonly used
Know the life cycle
Many things have a whole process from creation to destruction. This process is called the life cycle.
The React component also has its own life cycle. Understanding the life cycle of the component allows us to accomplish the desired functionality in the most appropriate place.
As the component goes through different life cycles, different life cycle functions are triggered, allowing us to write the logic in the most appropriate place.
Such as:
A component that calls network request data at build time should request the network in the componentDidMount() method.
Note: When we talk about the React lifecycle, we’re talking about the class lifecycle, because functional components don’t have lifecycle functions.
Life cycle analysis
Each class component contains “lifecycle methods” that you can override to execute at specific stages of the runtime. Let’s take a look at these lifecycle functions. Here’s the official lifecycle map:
Mount:
- When we mount a component, it is executed first
constructor
Construct methods to create components; - And then it calls
getDerivedStateFromProps
, it should return an object to updatestate
, if returnnull
Nothing is updated. - Call immediately after
render
Function to get theDOM
Structure (jsx
) and start renderingDOM
; - When the component is successfully mounted (
DOM
Render complete), will executecomponentDidMount
Life cycle function;
Update:
- When we go through the modification
props
, or callsetState
Modify internal state, or call directlyforceUpdate
Will be called againrender
Function to perform the update operation; - When the component’s
props
或state
Updates are triggered when changes occur. It callsgetDerivedStateFromProps
, it should return an object to updatestate
, if returnnull
Nothing is updated. - And then it calls
shouldComponentUpdate
And, based on the return value of this function, determine whether the output of the React component is affected by changes in the current state or props. - And then it calls
render
Function, called immediatelygetSnapshotBeforeUpdate
To perform the update operation - When the update is complete, a callback is made
componentDidUpdate
Life cycle function;
When unloading:
- When our component is no longer in use, it will be removed from
DOM
Remove (unload); - At this point, there will be a pullback
componentWillUnmount
Life cycle function;
Commonly used life cycle functions
render
render()
Copy the code
The Render () method is the only one that must be implemented in the class component.
When render is called, it checks for changes to this.props and this.state and returns one of the following types:
- The React elements. Usually by
JSX
To create. - An array or fragments could. make
render
Method can return multiple elements. - Portals. Can render child nodes to different
DOM
The child in the tree. - A string or numeric type. They are in
DOM
Is rendered as a text node - Boolean type or NULL. Nothing is rendered.
The Render () function should be pure, meaning that it returns the same result every time it is called without changing the component state, and it does not interact directly with the browser.
To interact with the browser, perform your actions in componentDidMount() or another lifecycle method. Keeping Render () pure makes the component easier to think about.
Note: If shouldComponentUpdate() returns false, render() is not called.
constructor
constructor(props)
Copy the code
If state is not initialized or method binding is not performed, there is no need to implement a constructor for the React component.
Constructor usually does only two things:
- By giving
this.state
Assignment object to initialize the internalstate
; - Bind an instance for an event (
this
);
constructor(props) {
super(props);
// Do not call this.setState() here
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
Copy the code
You can only assign this. State directly in the constructor. If you need to assign values in other methods, you should use this.setstate () instead.
Note: Avoid assigning props to state! This is a common mistake
componentDidMount
componentDidMount()
Copy the code
ComponentDidMount () is called immediately after the component is mounted (inserted into the DOM tree).
So where do you normally operate in componentDidMount?
- Depends on the
DOM
Operations can be performed here; - This is the best place to send network requests; (Official recommendation)
- You can add some subscriptions here
componentWillUnmount
Unsubscribe);
componentDidUpdate
componentDidUpdate(prevProps, prevState, snapshot)
Copy the code
ComponentDidUpdate () is called immediately after the update, not the first rendering.
- When the component is updated, it can be paired here
DOM
To operate; - If you update before and after
props
You can also choose to make a network request here. (For example, whenprops
The network request will not be executed if there is no change).
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props) :
if (this.props.userID ! == prevProps.userID) {this.fetchData(this.props.userID); }}Copy the code
You can also call setState() directly in componentDidUpdate(), but note that it must be wrapped in a conditional statement, as in the example above, otherwise it will cause an infinite loop.
Note: If shouldComponentUpdate() returns false, componentDidUpdate() is not called.
componentWillUnmount
componentWillUnmount()
Copy the code
ComponentWillUnmount () is called directly before the component is unmounted and destroyed.
- Perform the necessary cleanup actions, such as cleanup, in this method
timer
, cancel the network request or clear incomponentDidMount()
, etc.; componentWillUnmount()
中Should not callsetState()
Because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.
The code validates the common lifecycle functions described above:
import React, { Component } from 'react'
class HYTestCpn extends Component {
render() {
return <h2>HYTestCpn</h2>
}
componentWillUnmount() {
console.log('HYTestCpn componentWillUnmount')}}export default class App extends Component {
constructor(props) {
super(props)
this.state = {
counter: 0,}console.log('Call constructor method')}render() {
console.log('Call render method')
return (
<div>
<h2>Current count: {this.state.counter}</h2>
{this.state.counter <= 5 && <HYTestCpn />}
<button onClick={(e)= > this.increment()}>+1</button>
</div>)}increment() {
this.setState({
counter: this.state.counter + 1})},componentDidMount() {
console.log('Call componentDidMount method')}componentDidUpdate() {
console.log('Call componentDidUpdate method')}componentWillUnmount() {
console.log('Call componentWillUnmount method')}}Copy the code
Life cycles are not commonly used
In addition to the common lifecycle functions described above, there are some less common lifecycle functions:
shouldComponentUpdate
shouldComponentUpdate(nextProps, nextState)
Copy the code
ShouldComponentUpdate () is called before rendering when props or state changes. The default return value is true. This method is not called the first time you render or use forceUpdate().
- According to the
shouldComponentUpdate()
The return value of theReact
Whether the output of the component is currentstate
或props
Impact of changes. - The default behavior is
state
Components are rerendered every time they change. For the most part, you should follow the default behavior. - This method is used only asThe way performance is optimizedCame into being. Do not attempt to rely on this method to “block” rendering, as this may result
bug
.
Instead of writing it manually, we should first consider using the built-in PureComponent, which makes a shallow comparison between props and state and reduces the possibility of skipping necessary updates.
If you need to write it manually, you can compare this.props to nextProps and this.state to nextState and return false to tell React to skip the update. Note that returning false does not prevent child components from rerendering when state changes.
getDerivedStateFromProps
static getDerivedStateFromProps(props, state)
Copy the code
GetDerivedStateFromProps is called before the Render method is called, and is called both during the initial mount and during subsequent updates.
- It should return an object to update
state
, if returnnull
Nothing is updated. getDerivedStateFromProps
There is only one purpose for the component to existProps changeWhen the updatestate
, i.e.,state
The value of is dependent at any timeprops
.- This method does not have access to the component instance.
Note: This method fires before every render, regardless of the cause.
getSnapshotBeforeUpdate
getSnapshotBeforeUpdate(prevProps, prevState)
Copy the code
A function called before React updates the DOM to get pre-update information (such as scroll position).
- Any return value from this life cycle is passed as a parameter to
componentDidUpdate()
. - This usage is not common, but it may occur in
UI
For example, chat threads that need to handle scrolling positions in a special way. - Should return
snapshot
The value of (ornull
).
React also provides some out-of-date lifecycle functions that are no longer recommended.
For more information on the React lifecycle, see the React website