React组件生命周期

组件所有生命周期

'use strict';
import 'semantic-ui/semantic.min.css!';
import React from 'react';
import ReactDOM from 'react-dom'

class Hello extends React.Component {
    constructor() {
        super();
        this.state = {
            opacity: 1.0
        };
    }

    UNSAFE_componentWillMount() {
        console.log("组件将要挂载");
    }

    componentDidMount() {
        console.log("组件挂载完成");
        this.timer = setInterval(() => {
            var opacity = this.state.opacity;
            opacity -= 0.05;
            if (opacity < 0.1) {
                opacity = 1.0;
            }
            this.setState({
                opacity: opacity
            });
        }, 500);
    }
    UNSAFE_componentWillReceiveProps() {
        console.log("组件将要接收prop,这个方法在初始化render时不会被调用。");
    }

    UNSAFE_componentWillUpdate() {  //初始化并没有调用
        console.log('组件将要更新 render前');
    };
    componentDidUpdate() {  //初始化并没有调用
        console.log('组件将要更新 render后');
    };
    componentWillUnmount() {
        console.log('在组件从 DOM 中移除的时候立刻被调用');
        clearInterval(this.timer);
    }
    componentDidCatch() {
        console.log("错误处理");
    }



    render() {
        return (<div>组件生命周期
                 <p style={{ opacity: this.state.opacity }}>hello world</p></div>)
    }
}

ReactDOM.render(<Hello />, document.getElementById('app'));

 

shouldComponentUpdate

'use strict';
import 'semantic-ui/semantic.min.css!';
import React from 'react';
import ReactDOM from 'react-dom'

class Hello extends React.Component {
    constructor() {
        super();
        this.state = {
            n:1
        };
    };
    handleClick() {
        this.setState({
            n:this.state.n
        });
    }

    shouldComponentUpdate(nextProps,nextState) {
        //减少重复渲染 不需要重复更新组件时使用
        console.log(nextProps);
        console.log(nextState);
        return nextState.n > this.state.n;
    }
    render() {
        return (
            <div>
             <p>{this.state.n}</p>
                <button onClick={()=>this.handleClick()}>点击</button>
            </div>
        )
    }

}

ReactDOM.render(<Hello />, document.getElementById('app'));

 

 

posted @ 2020-02-25 20:17  bradleydan  阅读(97)  评论(0)    收藏  举报