preface
A life cycle is the stages from the beginning to the end of something. It’s like dividing a person’s life into stages from birth to death. You have to name them at birth, not adulthood or death. The React instance starts creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and unmounting the React instance. This is the React lifecycle. There are event hooks for each phase. Users can invoke specific methods at specific stages. The properties inside each phase of the component are different, so typically a particular hook does a particular thing.
React lifecycle diagram
[1] Past
[2] Now
React lifecycle evolution
With so many lifecycle hooks, there are really only three processes: mount, update, and unload. Mount and unload are performed only once, and updates are performed multiple times.
A complete React component lifecycle calls the following hooks in sequence
[1] Evolution of life cycle
Before React 16.3
mount
- constructor
- componentWillMount
- render
- componentDidMount
update
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
uninstall
- componentWillUnmount
now
mount
- constructor
- getDerivedStateFromProps
- render
- componentDidMount
update
- getDerivedStateFromProps
- shouldComponentUpdate
- render
- getSnapshotBeforeUpdate
- componentDidUpdate
uninstall
- componentWillUnmount
[2] Discard and add
The original (pre-React V16.0) life cycle was deprecated after Fiber in React V16 because async rendering will be executed multiple times before render is enabled. So in addition to shouldComponentUpdate, other all functions before the render function (componentWillMount componentWillReceiveProps, ComponentWillUpdate) are replaced by getDerivedStateFromProps.
The following lifecycle hooks will be phased out. See the features? They are all hooks with Will
- componentWillMount
- componentWillReceiveProps
- componentWillUpdate
The following two lifecycle hooks are introduced
- getDerivedStateFromProps
- getSnapshotBeforeUpdate
[3] Be careful
- GetDerivedStateFromProps = static (); / / React ignores getDerivedStateFromProps as static
- GetDerivedStateFromProps this is undefined
React lifecycle methods
【1】constructor(props) : initialize hook functions
The React data is initialized by constructor(), which accepts two parameters: props and context. When you want to use these two parameters inside a function, you need to pass them in with super(). If there is no initialization state and no binding method, it is usually not necessary to implement a constructor for the React component.
Note:
- Whenever constructor() is used, you must write super(), otherwise this will point to an error.
- Instead of calling setState() in the constructor, just set the initial state to this.state.
The React constructor is usually only used for two purposes:
- Initialize local state by assigning an object to this.state
- Bind event handler methods to instances
constructor(props) { super(props); This. state = {color: props. Color}; }Copy the code
[2] componentWillMount() : function triggered when a component is about to be mounted
This is the lifecycle hook before the component is mounted to the DOM. ComponentWillMount () is used less often, and more often for server-side rendering. It represents the process when the component has gone through a constructor() initialization of data, but has not yet rendered the DOM.
[3] Render () : function triggered when the component is mounted
The Render function is the only required method in the class component; the rest of the lifecycle is not required to be written. Components are rendered to this life cycle, and displayed components are determined by the return value of the Render () life cycle. The Render function inserts the DOM structure generated by JSX. React generates a virtual DOM tree. At each component update, React uses its diff algorithm to compare the old and new DOM trees before and after the update, find the smallest dom nodes that differ, and re-render them.
[4] componentDidMount() : a function triggered when the component is mounted
This is the lifecycle hook after the component is mounted to the DOM. When the component is rendered for the first time and the DOM node has been generated, an Ajax request can be called from here and the component will be rendered again after the setState data is returned
[5] componentWillUnmount () : function triggered when a component is about to be destroyed
This is the lifecycle hook before component uninstallation, where component uninstallation and data destruction are completed.
[6] componentWillReceiveProps (nextProps) : the parent component changed props triggered when the value function
-
This is often used when props need to re-render the component after accepting changes to the parent component
-
Accept a parameter, nextProps
-
The component is rerendered by comparing the state of nextProps to the state of the current component
componentWillReceiveProps (nextProps) { nextProps.isOpen ! == this.props.isOpen && this.setState({ isOpen:nextProps.isOpen }, () => {// Update state to nextProps, the second argument in setState (callback) can print out the new state})}
[7] shouldComponentUpdate(nextProps, nextState) : a function that is triggered when a component is to be updated
- This lifecycle hook is a switch that determines whether an update is needed and is used primarily to optimize performance (partial updates). If a developer calls this.forceUpdate to force an update, the React component ignores this hook.
- Components need to be rerendered only if their state changes. The shouldComponentUpdate lifecycle hook exposes two parameters. Developers can compare this.props and nextProps, this.state and nextState to determine if the state has changed, and return true or false accordingly.
- The only way to control the life cycle of a component’s re-rendering is to setState in react and the component will enter the re-rendering process. Return false prevents the component from updating
- Rerendering of the React parent will result in rerendering of all of its children. In this case, we do not need to re-render all of the children, so we need to make decisions in the life cycle of the children
[8] componentWillUpdate (nextProps, nextState) : a function triggered when a component is to be updated
ShouldComponentUpdate after the lifecycle hook returns true, the component goes to the re-rendering process and goes to componentWillUpdate, where you can also get nextProps and nextState.
[9] componentDidUpdate(prevProps,prevState) : a function triggered when component updates are complete
React will only go into componentDidmount after the first initialization, and then every time you re-render it will go into the life cycle. So here you can get prevProps and prevState, Props and state before the update.
[10] Static getDerivedStateFromProps(nextProps, prevState) : Static method lifecycle hook
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, and if null is returned, nothing is updated. Why is the getDerivedStateFromProps lifecycle hook designed as a static method? Instead of calling instance methods or setsState, a static function getDerivedStateFromProps was used to replace several other deprecated lifecycle functions. Forces developers to perform only side-effect actions before render, and is limited to deciding on new states based on props and state.
[11] getSnapshotBeforeUpdate(prevProps, prevState) : Save the state snapshot
It is used to replace the componentWillUpdate lifecycle hook function. The common use case of componentWillUpdate is to read the current state of a DOM element before the component is updated, and the corresponding processing in componentDidUpdate.
The difference between the two is:
- When asynchronous render mode is enabled in React, the DOM element states read in render are not always the same as those read in commit. This makes it unsafe to use the DOM element states read in componentWillUpdate in componentDidUpdate because the values are likely to be invalid.
- GetSnapshotBeforeUpdate is called before final render, which means that the DOM element states read in getSnapshotBeforeUpdate are guaranteed to be the same as in componentDidUpdate. Any values returned by this life cycle are passed as arguments to componentDidUpdate().
Four, the instance,
[1] Mount stage
Create a child component and add rendering to the parent
Import React,{Component} from 'React' class Child extends Component{// Initializing constructor(constructor){console.log('01 constructor ') Super (props) this.state={}} // Lifecycle function triggered when component is about to mount componentWillMount(){console.log('02 component is about to mount ')} // Lifecycle function triggered when component is ready to mount ComponentDidMount (){console.log('04 componentDidMount complete ')} // Render (){console.log('04 componentDidMount complete ') return( <div>Child component </div>)}} export default ChildCopy the code
The console prints the results in the following order:
01 Constructor 02 component to mount 03 Data render 04 component to mount complete
[2] Update stage
ShouldComponentUpdate () shouldComponentUpdate (); shouldComponentUpdate (); shouldComponentUpdate (); shouldComponentUpdate (); NextState is the updated data value, and these two values can be obtained in this function. In the second step, after confirming to update the data, componentWillUpdate will update the data. In the third step, the data is still render, and the data is changed to render again. The fourth step is componentDidUpdate data update is completed.
import React, { Component } from 'react' class Child extends Component { constructor(props) { super(props) this.state = { msg: 'I am a MSG data'}} // Whether to update data, ShouldComponentUpdate (nextProps, nextState) {console.log('01 whether to update data ') return true; // Return true, ComponentWillUpdate () {console.log('02 componentWillUpdate ')} // componentDidUpdate() { Console. log('04 component update completed ')} // Update data method setMsg() {this.setstate ({MSG: <div> {this.state.msg} <button onClick={() => render() {console.log('03 render') return (<div> {this.state.msg} <button onClick={() => This.setmsg ()}> export default Child </button> </div>Copy the code
Click the button to update the data, and the console prints the results in the following order:
01 Whether to update data 02 Components to mount 03 Data Render 04 Components are updated
Five, the reference
React official website: zh-hans.reactjs.org/
The article is updated every week. You can search “Front-end highlights” on wechat to read it in the first time, and reply to [Books] to get 200G video materials and 30 PDF books