React —— React中生命周期详解及案例分享

文章目录

  • 一、什么是生命周期
  • 二、生命周期的三个阶段
    • 1.初始化阶段
    • 2.更新阶段
    • 3.卸载阶段
  • 三、生命周期总结
    • 1.重要的钩子
    • 2.即将废弃的钩子
  • 四、案例分享

一、什么是生命周期

·组件从创建到死亡,会经过一些特定的阶段。

·React组件中包含一系列钩子函数{生命周期回调函数},会在特定的时刻调用。

·我们在定义组件的时候,会在特定的声明周期回调函数中,做特定的工作。

​​​​​​​

组件的生命周期可分成三个状态:

  • Mounting(挂载):已插入真实 DOM
  • Updating(更新):正在被重新渲染
  • Unmounting(卸载):已移出真实 DOM

二、生命周期的三个阶段

1.初始化阶段

ReactDOM.render()触发,般在这个钩子中做一些初始化的事情,如:开启定时器,发送网络请求,订阅消息等。

  • ·constructor()
  • · getDerivedStateFromProps() 从Props获得派生状态 static 静态方法 state状态取决于props使用
  • ·render()
  • ·componentDidMount() ====>`常用` //在页面渲染完成,组件已挂载完成时调用。

2.​​​​​​​更新阶段

由组件内部的this.setState()或者父组件的render触发。

  • ·getDerivedStateFromProps()  从Props获得派生状态
  • · shouldComponentUpdate() 组件应该更新
  • ·render()
  • ·getSnapshotBeforeUpdate(beforeprops,beforestate) 在更新前获得快照  返回null
  • ·componentDidUpdate()

​​​​​​​

3.卸载阶段

ReactDOM.unmountComponentAtNode()触发

- componentWillUnmount() ===>`常用`

一般在这个钩子中做一些收尾的事情,如:关闭定时器、取消订阅消息

三、生命周期总结

1、重要的钩子

  • render:初始化渲染或者更新渲染调用
  • componentDidMount() :组件挂载之后调用,此时可以操作DOM,ajax请求,订阅信息等。
  • componentWillUnmount(): 组件卸载后调用,做一些收尾工作,如:清理定时器,取消网络请求等。

2、即将废弃的钩子

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

`ps`:现在使用会出现警告,之后版本可能需要加上UNSAFE_前缀才能使用,以后可能会被彻底废弃,不建议使用

推测React团队认为提高使用成本将会间接影响我们,让我们去适应新的钩子,所以加上这个

四、案例分享

要求,页面中有一个小盒子会自动行走,当点击卸载组件时,页面组件消失。如下图所示:

 示例代码:

<!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>

猜你喜欢

转载自blog.csdn.net/Bonsoir777/article/details/127631571