react学习(二)

发布时间 2023-04-03 15:17:49作者: 小白不白10

生命周期

import React from "react";
class LifeCycle extends React.Component{
    //React.StrictMode会让声明周期执行两次
    constructor(props){
        super(props) 
        this.state={
            count:1
        }
        console.log('生命周期constructor')   //初始化state,绑定this  
    }
    componentDidMount(){
        //渲染完成之后执行
        console.log('生命周期componentDidMount') //发送网络请求
    }
    componentDidUpdate(){
        //更新之后执行
        console.log('生命周期componentDidUpdate') 
    }
    shouldComponentUpdate(){
        //false render就不执行了(阻止渲染)
        console.log('生命周期shouldComponentUpdate') 
        return true
    }
    componentWillUnmount(){
        //销毁之前执行
        console.log('生命周期componentWillUnmount')
    }
    handleClick=()=>{
        this.setState({
            count:this.state.count+1
        })
    }
    render(){
        //渲染执行还没渲染完
        console.log('生命周期render')
        return(
            <div>
                生命周期:{this.state.count}
                <button onClick={this.handleClick}>点击</button>
            </div>
        )
    }
}
export default LifeCycle