React - Detailed explanation and case sharing of life cycle in React

Article Directory

  • 1. What is the life cycle
  • Two, the three stages of the life cycle
    • 1. Initialization phase
    • 2. Update phase
    • 3. Uninstall phase
  • 3. Life cycle summary
    • 1. Important Hooks
    • 2. The soon-to-be-discarded hook
  • 4. Case sharing

1. What is the life cycle

· Components go through some specific stages from creation to death.

The React component contains a series of hook functions {life cycle callback function}, which will be called at a specific moment.

When we define a component, we will do specific work in a specific life cycle callback function.

​​​​​​​

The life cycle of a component can be divided into three states:

  • Mounting: inserted into the real DOM
  • Updating: is being re-rendered
  • Unmounting: moved out of the real DOM

Two, the three stages of the life cycle

1. Initialization phase

Triggered by ReactDOM.render(), generally do some initialization in this hook, such as: start timer, send network request, subscribe message, etc.

  • ·constructor()
  • · getDerivedStateFromProps() Obtain the derived state from Props static static method state state depends on the use of props
  • ·render()
  • ·componentDidMount() ====>`Common` //Called when the page rendering is completed and the component has been mounted.

2. ​​​​​​Update stage

Triggered by this.setState() inside the component or the render of the parent component.

  • · getDerivedStateFromProps() Get derived state from Props
  • · shouldComponentUpdate() The component should be updated
  • ·render()
  • ·getSnapshotBeforeUpdate(beforeprops,beforestate) Get a snapshot before updating and return null
  • ·componentDidUpdate()

​​​​​​​

3. Uninstall phase

Triggered by ReactDOM.unmountComponentAtNode()

- componentWillUnmount() ===>`Common`

Generally, do some finishing things in this hook, such as: closing the timer, unsubscribing the message

3. Life cycle summary

1. The important hook

  • render: Initialize rendering or update rendering calls
  • componentDidMount() : Called after the component is mounted. At this time, DOM, ajax request, subscription information, etc. can be operated.
  • componentWillUnmount(): Called after the component is unmounted to do some finishing work, such as: cleaning timers, canceling network requests, etc.

2. The soon-to-be-discarded hook

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

`ps`: There will be a warning when using it now, and the version in the future may need to be prefixed with UNSAFE_, and it may be completely abandoned in the future, so it is not recommended to use

It is speculated that the React team believes that increasing the cost of use will indirectly affect us, let us adapt to the new hook, so add this

4. Case sharing

Requirements, there is a small box on the page that will move automatically, and when you click to uninstall the component, the page component disappears. As shown below:

 Sample code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生命周期的应用</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box1 {
            width: 100px;
            height: 100px;
            background: #bfa;
        }

        button {
            margin: 20px 0 0 20px;
            height: 30px;
        }
    </style>
</head>

<body>
    <div id="root"></div>
    <!-- 引入文件 -->
    <script src="../JS/react.development.js"></script>
    <script src="../JS/react-dom.development.js"></script>
    <script src="../JS/babel.min.js"></script>

    <script type="text/babel">

        class BoxRun extends React.Component {
            state = {
                a: 0
            }
            componentDidMount() {
                this.timer = setInterval(() => {
                    if (this.state.a > 300) {
                        this.state.a = 0;
                    }
                    this.setState({ a: this.state.a += 50 });
                    console.log(123);
                }, 1000)
            }
            // 组件将要卸载之前关闭定时器
            componentWillUnmount(){
                clearInterval(this.timer);
            }
            // 卸载组件
            removeBox = () => {
                ReactDOM.unmountComponentAtNode(document.getElementById('root'));
            }
            render() {
                return (
                    <div>
                        <div className="box1" style={
   
   { "transform": `translate(${this.state.a}px)` }}>我是一个会动的小盒子~</div>
                        <button onClick={this.removeBox}>卸载组件</button>
                    </div>
                )
            }
        }

        // 渲染真实dom到页面
        ReactDOM.render(<BoxRun />, document.getElementById('root'));
    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/Bonsoir777/article/details/127631571