React、react生命周期、react生命周期运行过程、shouldComponentUpdate的用法

React、react生命周期、react生命周期运行过程

1、创建阶段

    constructor(){
        super()
        console.log('执行构造函数')
        this.state={
            num:1
        }
    }
    UNSAFE_componentWillMount(){
        console.log('即将渲染')
    }
    render(){
        console.log('渲染页面')
        return(
            

{this.state.num}

) } componentDidMount(){ console.log('组件完成挂载,这个方法执行完,组件就开始运行了,可以在这里获取数据') }

2、组件运行阶段:根据组件state跟props的改变,有选择性的触发0次或者多次

componentWillReceiveProps(){
        console.log('此方法被触发,证明父组件为子组件传递了新的属性值(首次不会触发函数)')
    }
    shouldComponentUpdate(nextProps,nextState){//控制组件是否重新渲染
        console.log('组件是否需要被更新,此时,组件尚未被更新,但是,state 和 props 肯定是最新的')
        console.log(this.state.num)
        console.log(nextState)
        if(this.state.num===nextState.num){//性能优化,如果页面跟数据一致,就不更新了
            return false
        }else{
         return true
        }
    }
    componentWillUpdate(){
        console.log('组件将要被跟新,此时内存中的虚拟dom跟页面上的虚拟dom都是旧的')
    }
    //render:此时,又要重新根据最新的 state 和 props 重新渲染一颗内存中的虚拟 DOM 树,当 render 调用完毕,内存中的旧 DOM 树,已经被新 DOM 树替换了,此时页面还是旧的
    componentDidUpdate(){
        console.log('组件更新完毕,此时state跟内存dom页面dom都一致了')
    }

3、组件销毁阶段,一辈子执行一次

componentWillUnmount(){
        console.log('组件将要被销毁,此时还可以正常使用')
    }

你可能感兴趣的:(React)