The concept of Life Cycle is widely used, especially in many fields such as economy, environment, technology, society and so on. Its basic meaning can be colloquically understood as the whole process from Cradle to Grave
React component life cycle consists of creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and unmounting
The three stages
As you can see from the figure, the React component creation actually has multiple life cycles, which can be divided into three phases
Render phase
It is mainly used to calculate some current states
Features: pure and contains no side effects. React may be paused, suspended, or restarted.
The Pre – the commit phase
How about declaring commit? React actually updates the DOM node while mapping the current state to the DOM. There is no actual DOM update during the pre-commit phase
Features: DOM can be read
The Commit phase
React updates the state to the actual DOM nodes
Features: You can use DOM, run side effects, and schedule updates.
Three types of
When creating
When a component instance is created and inserted into the DOM, its lifecycle is invoked in the following order
constructor()
: a component constructor that is called before the component is updated to the interfaceconstructor
- Used to initialize internal state. Rarely used
- Only can be directly modified
state
The place where
getDerivedStateFromProps()
: Used to initialize some internal state from an external property- when
state
Need fromprops
Used during initialization - Try not to use, maintain
state/props
State consistency adds complexity - Every time
render
Will be called - Typical scenario: Form controls get default values
- when
render()
: a lifecycle method that the component must define to describeDOM
structurecomponentDidMount()
: Used for data requests, defining some external resources and other side effects- Called after UI rendering is complete
- Execute only once
- Typical scenario: Obtaining external resources
componentDidMount
If we place AJAX requests in other functions in the lifecycle, there is no guarantee that the request will require a response only after the component has been mounted.
If our data request completes before the component is mounted, and the setState function is called to add data to the component state, an error will be reported for the unmounted component.
Making an AJAX request in the componentDidMount function avoids this problem.
update
Updates are triggered when a component’s props or state changes. The lifecycle of component updates is called in the following order
getDerivedStateFromProps()
: Used to initialize some internal state from an external propertyshouldComponentUpdate(nextProps, nextState)
: Tells the component whether it needs to be rerendered for performance optimizations, such as determining the specificationprops
Components are rerendered only when changes occur- Determine the virtual
DOM
Whether you need to redraw - In general, this can be done by
PureComponent
automatically - Typical scenario: Performance optimization
- Determine the virtual
render()
getSnapshotBeforeUpdate(prevProps, prevState)
- Called before the last render output (submitted to the DOM node),
state
Has been updated - with
componentDidUpdate
Collocation is used - Typical scenario: Capture the DOM state before render
- Called before the last render output (submitted to the DOM node),
componentDidUpdate(prevProps, prevState)
- Called every time the UI is updated
- Typical scenario: The page needs to be based on
props
Change to retrieve data again
shouldComponentUpdate
ShouldComponentUpdate allows us to manually determine whether or not to update a component. Setting a reasonable return value for the component based on its application scenario helps us avoid unnecessary updates.
When unloading
When a component is removed from the DOM, when a component disappears from the page, it needs to be destroyed
The following methods are called:
componentWillUnmount()
: Do something to free up resources and uninstall side effects
In this method necessary cleanup actions can be performed, such as clearing timer, canceling network request or clearing in
The lifecycle is required in error handling scenarios
The following methods are called when an error is thrown in the rendering process, lifecycle, or constructor of a child component
static getDerivedStateFromError()
componentDidCatch()
Common Usage Scenarios
componentDidMount
+componentWillUnmount
Implement timers, such asDigital clock
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(() = > this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()}); }render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(<Clock />.document.getElementById("root"));
Copy the code
getSnapshotBeforeUpdate(prevProps, prevState)
+componentDidUpdate()
Capture scrollbar position
There’s a list of what’s going on in reality — list,
- It appears at the top of the list every time a new dynamic is created
- List supports scrolling so that users can view historical messages
If you don’t use getSnapshotBeforeUpdate, the scroll bar will scroll down every time a message comes in, so it won’t stay in place
Because each incoming message creates a new DOM node at the top,
To avoid this problem, we need to know
- Knowing the current height of the entire container before the page is updated,
- Know the new height of the container after the page is updated
- Compare the old height with the new height
- The height difference is added to the container after each page update
scrollTop
上
This ensures that the scrollbar stays in its current position even when new messages come in
// SnapshotSample.less
.snapshotSample {
height: 100px;
padding: 20px;
overflow: auto;
border: 1px solid #eee;
widows: 300px;
}
Copy the code
import React, { PureComponent } from "react";
import styles from "./SnapshotSample.less";
export default class SnapshotSample extends PureComponent {
constructor(props) {
super(props);
this.listRef = React.createRef();
this.state = {
list: [],}; }handleNewMessage() {
this.setState((prev) = > ({
list: [`msg ${prev.list.length}`. prev.list], })); }componentDidMount() {
for (let i = 0; i < 20; i++) this.handleNewMessage();
this.interval = setInterval(() = > {
if (this.state.list.length > 200) {
clearInterval(this.interval);
return;
}
this.handleNewMessage();
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// Do we add new items to the list?
// Capture the scroll position so we can adjust the scroll position later.
if (prevState.list.length < this.state.list.length) {
const list = this.listRef.current;
return list.scrollHeight - list.scrollTop;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
// If our snapshot has a value, we just added a new item,
// Adjust the scroll position so that these new items do not push the old items out of the view.
// (where snapshot is the return value of getSnapshotBeforeUpdate)
if(snapshot ! = =null) {
const list = this.listRef.current; list.scrollTop = list.scrollHeight - snapshot; }}render() {
return (
<div className={styles.snapshotSample} ref={this.listRef}>
{this.state.list.map((msg) => (
<div key={msg}>{msg}</div>
))}
</div>); }}Copy the code
summary
- Understand the React component lifecycle approach
- Understand the usage scenarios for the lifecycle
The last
This article is shallow, you are welcome to see the officer comments left your opinion!
Feel the harvest of the students welcome to like, pay attention to a wave!
Past oliver
- 15 front-end hd knowledge map, strongly recommended collection
- What is the principle of qr code scanning login
- Let me tell you about some awesome NPM packages
- The most complete ECMAScript walkthrough
- Front end developers should know Centos/Docker/Nginx/Node/Jenkins (🍡 long)