This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
Today we’ll take a look at the life cycle of the React component, learn about the three phases of the life cycle in both the old and new versions of React, and finally talk briefly about the virtual DOM and diff algorithms
1. Component lifecycle
1.1 understand
- Components go through specific phases from creation to death.
- The React component contains a series of tick functions (lifecycle callbacks) that are called at specific times.
- When we define a component, we do certain things in certain lifecycle callbacks.
1.2 Introduction Cases
Requirements: Define components that do the following:
- Animates the specified text with a gradient show/hide
- It takes 2 seconds to go from completely visible to completely gone
- Click the Deactivate button to uninstall the component from the interface
// Create a component
// Lifecycle callback <=> lifecycle hook function <=> lifecycle hook function <=> lifecycle hook function
class Life extends React.Component{
state = {opacity:1}
death = () = >{
// Uninstall the component
ReactDOM.unmountComponentAtNode(document.getElementById('test'))}// The component hangs
componentDidMount(){
console.log('componentDidMount');
this.timer = setInterval(() = > {
// Get the original state
let {opacity} = this.state
//减小0.1
opacity -= 0.1
if(opacity <= 0) opacity = 1
// Set new transparency
this.setState({opacity})
}, 200);
}
// The component will be unmounted
componentWillUnmount(){
// Clear the timer
clearInterval(this.timer)
}
// After initial rendering and status update
render(){
console.log('render');
return(
<div>
<h2 style={{opacity:this.state.opacity}}>What if you can't React?</h2>
<button onClick={this.death}>Don't live</button>
</div>)}}// Render component
ReactDOM.render(<Life/>.document.getElementById('test'))
Copy the code
1.3 Three Stages of the Life Cycle (old)
1.3.1 Initialization Phase
Triggered by reactdom.render () — initial render
constructor()
Constructor in a class componentcomponentWillMount()
— Component about to be mounted [about to be obsolete]render()
— Mount componentscomponentDidMount()
Do some initialization in this hook, such as start timer, send network request, subscribe message
class Count extends React.Component{
/ / the constructor
constructor(props){
alert('constructor')
console.log('Count---constructor');
super(props)
// Initialization state
this.state = {count:0}
}
add = () = > {
const {count} = this.state
this.setState({count: count+1})}// The hook to be mounted by the component
componentWillMount(){
alert('componentWillMount')
console.log('Count---componentWillMount');
}
render(){
alert('render')
console.log('Count---render');
const {count} = this.state
return(
<div>
<h1>Current count: {count}</h1>
<button onClick={this.add}>I + 1 point</button>
</div>)}// The component has mounted the hook
componentDidMount(){
alert('componentDidMount')
console.log('Count---componentDidMount');
}
}
ReactDOM.render(<Count/>.document.getElementById('test'))
Copy the code
1.3.2 Update phase
Parent component rerender trigger
componentWillReceiveProps()
— Accept attribute parameters (not first time) [about to be discarded]
Then call the following hook function
This. SetSate ()
shouldComponentUpdate()
Whether the component should be updated (returned by defaulttrue
)
Then call the following hook function
ForceUpdate () forceUpdate()
componentWillUpdate()
— Component to be updated [obsolete]render()
— Component updatescomponentDidUpdate()
The component has been updated
1.3.3 Uninstalling Components
Triggered by ReactDOM. UnmountComponentAtNode ()
componentWillUnmount()
The component is about to be uninstalled
1.4 Three Phases of the Life Cycle (New)
1. Initialization phase
Triggered by reactdom.render () — first render
constructor()
Constructor in a class componentstatic getDerivedStateFromProps(props, state)
Get a derived state from props [New]render()
— Mount componentscomponentDidMount()
— Component mount complete comparison == Common ==
2. Update phase
ForceUpdate () triggered or forced by a component’s internal this.setsate () or parent’s rerender
getDerivedStateFromProps()
Get a derived state from props [added]shouldComponentUpdate()
Whether the component should be updated (returned by defaulttrue
)render()
— Mount componentsgetSnapshotBeforeUpdate()
— Get snapshot before update [added]componentDidUpdate(prevProps, prevState, snapshotValue)
The component has been updated
3. Uninstall components
Triggered by ReactDOM. UnmountComponentAtNode ()
componentWillUnmount()
The component is about to be uninstalled
1.5 Important hooks
render
Initialize render or update render callcomponentDidMount
: Enables listening and sends Ajax requestscomponentWillUnmount
: Do some finishing touches, such as clearing timers
1.6 Hooks to be abandoned
componentWillMount
componentWillReceiveProps
componentWillUpdate
If used now, there will be a warning, the next big version will need to be prefixed with UNSAFE_ to use, it may be completely deprecated, not recommended.
2. Virtual DOM and DOM Diffing algorithm
2.1 Basic schematic diagram
Detailed principles can be seen before learning Vue source code on diff notesDiff algorithm and virtual DOM- SNabbDOM – minimum update principle analysis – handwritten source -updateChildren
2.2 Classic interview questions about key
- What do react/ Vue keys do? (What’s the inner workings of Key?)
- Why is it best not to use index for key when iterating through a list?
2.2.1 Functions of Keys in the Virtual DOM
-
To put it simply: The key is the identity of the virtual DOM object and plays an extremely important role in updating the display.
-
React generates a new virtual DOM based on the new data. Then React makes a diff comparison between the new virtual DOM and the old virtual DOM. The comparison rules are as follows:
- The same key as the new virtual DOM was found in the old virtual DOM:
- If the content in the virtual DOM has not changed, use the real DOM directly
- If the content in the virtual DOM changes, a new real DOM is generated, which then replaces the previous real DOM in the page
- The same key as the new virtual DOM was not found in the old virtual DOM
- Create a new real DOM from the data and render it to the page
- The same key as the new virtual DOM was found in the old virtual DOM:
2.2.2 Possible Problems caused by using index as key
-
If the data is added in reverse order, deleted in reverse order and other out-of-order operations, unnecessary real DOM updates will be generated
-
If the structure also contains input class DOM: error DOM update ==> interface has problems
-
Attention! It is ok to use index as key if there is no order breaking operation such as adding or deleting data in reverse order and only used for rendering list for display
2.2.3 How to select a Key during Development?
- It is better to use the unique identifier of each piece of data as the key, such as ID, mobile phone number, ID number, student number and other unique values
- If you are sure to simply display data, index is fine