react学习笔记--生命周期+实例

react学习笔记–生命周期+实例

下面是一张生命周期图
具体使用会在实例中介绍到
在这里插入图片描述

  1. 组件的三个生命周期状态:
    • Mount:插入真实 DOM
    • Update:被重新渲染
    • Unmount:被移出真实 DOM
  2. React 为每个状态都提供了勾子(hook)函数
    • componentWillMount()
    • componentDidMount()
    • componentWillUpdate()
    • componentDidUpdate()
    • componentWillUnmount()
  3. 生命周期流程:
    a. 第一次初始化渲染显示: ReactDOM.render()
    • constructor(): 创建对象初始化state
    • componentWillMount() : 将要插入回调
    • render() : 用于插入虚拟DOM回调
    • componentDidMount() : 已经插入回调
      b. 每次更新state: this.setSate()
    • componentWillUpdate() : 将要更新回调
    • render() : 更新(重新渲染)
    • componentDidUpdate() : 已经更新回调
      c. 移除组件: ReactDOM.unmountComponentAtNode(containerDom)
    • componentWillUnmount() : 组件将要被移除回调

下面为一个应用实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="example"></div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/prop-types.js"></script>
    <script src="../js/babel.min.js"></script>
    
    <script type="text/babel">
        class Life extends React.Component{
            constructor(props){
                super(props)
                this.state = {
                    opacity:1
                }
                this.distroyComponent = this.distroyComponent.bind(this);
            }
            //渲染组件后更新  ,生命周期回调函数 constructor componentWillMount render, componentDidMount
            //而且它们在特定时间调用 
            componentDidMount() {
             this.intervalId = setInterval(function(){
                 console.log("asdasd");
                    let {opacity} = this.state;
                    opacity -= 0.01;
                    if(opacity <= 0){
                       opacity = 1; 
                    }
                    this.setState({opacity});
                }.bind(this),20);
            }
            //卸载组件的方法
            distroyComponent(){
               ReactDOM.unmountComponentAtNode(document.getElementById('example'));
            }
            //卸载组件的方法前前,需要做的操作(必定调用),清除定时器
            componentWillUnmount(){
                clearInterval(this.intervalId);
            }
			//必须嵌套一个div
            render() {
                const opacity = this.state.opacity;
                return (
                    <div>
                        <h2 style ={{opacity:opacity}}>{this.props.msg}</h2>
                        <button onClick={this.distroyComponent}>不活了</button>
                    </div>
                )
            }
        }
        ReactDOM.render(<Life msg = "react太难了"/>,document.getElementById('example'));
    </script>
</body>
</html>
发布了84 篇原创文章 · 获赞 204 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44983621/article/details/101014279