React组件的生命周期的使用

时间:2023-02-01 22:00:21 类型:React
字号:    

对生命周期的理解:

       1, 组件从创建到死亡,它会经历一些特定的阶段

       2, React组件包含一系列钩子函数(生命周期回调函数),会在特定的时刻被调用

      3, 我们在定义组件时,会在特定的生命周期回调函数中,做特定的工作

页面最后有对生命周期使用的总结:


生命周期图02.png

//1. 创建类式组件
        //生命周期回调函数 <=> 生命周期钩子函数 <=> 生命周期函数 <=> 生命周期钩子
        //对生命周期的理解:
        //1, 组件从创建到死亡,它会经历一些特定的阶段
        //2, React组件包含一系列钩子函数(生命周期回调函数),会在特定的时刻被调用
        //3, 我们在定义组件时,会在特定的生命周期回调函数中,做特定的工作
        class Life extends React.Component{
            //初始化状态
            state = {opacity:1}
            //组件挂载完毕
            componentDidMount(){
                this.timer = setInterval(()=>{
                    let {opacity} = this.state
                    opacity -= 0.1
                   
                    if(opacity <= 0) {
                        console.log(opacity);
                        opacity = 1
                    }
                    console.log(opacity);
                    this.setState({opacity:opacity})
                },1000)
            }
            componentWillUnmount(){
                clearInterval(this.timer);
            }
            //调用时机: 初始化渲染,状态更新之后
            render() {
                //render 调用几次  1 + n(第一次渲染,然后当 state状态更新时,所以这里每当state更新一次,就会再次一次)
                //所以把setInterval放在这里不合适
                /* setInterval(()=>{
                    let {opacity} = this.state
                    opacity -= 0.1
                    
                    if(opacity <= 0) {
                        console.log(opacity);
                        opacity = 1
                    }
                    console.log(opacity);
                    this.setState({opacity:opacity})
                },1000) */
                return (
                    <div>
                        <h1 style={{opacity:this.state.opacity}}>学不会, 怎么办</h1>
                        <button onClick={this.die}>不活了</button>
                    </div>
                )
            }
            die = (event)=>{
                //console.log(event.target);
                //卸载组件
                ReactDOM.unmountComponentAtNode(document.getElementById("test"));
            }
        }
        ReactDOM.render(<Life/>,document.getElementById("test"))

旧的生命周期的调用

 class Count extends React.Component{
            state = {count:0}
            //生命周期函数 挂载时如下
            //1, constructor(构造器)
            //2, componentWillMount(组件将要挂载)
            //构造器
            constructor(props){
                console.log("Count---constructor");
                super(props)
            }
            //组件将要挂载的钩子
            componentWillMount(){
                console.log("Count---componentWillMount");
            }
            //组件挂载完毕的钩子
            componentDidMount(){
                console.log("Count---componentDidMount");
            }
           
            componentWillUnmount(){
                console.log("Count---componentWillUnmount");
            }

            //组件是否应该更新(true---go,false---stop) 默认返回true
            shouldComponentUpdate(){
                console.log("Count---shouleComponentUpdate");
                return true
                //如果是false, 就不再往下走了
            }
            //组件将要更新的钩子
            componentWillUpdate(){
                console.log("Count---componentWillUpdate");
            }
            //组件更新完毕
            componentDidUpdate(){
                console.log("Count---componentDidUpdate");
            }
            render(){
                console.log("Count---render");
                return (
                    <div>
                        <h1>当前的统计总数为: {this.state.count}</h1>
                        <button onClick={this.add}>点击+1</button>
                        <button onClick={this.die}>卸载组件</button>
                        <button onClick={this.force}>不更改任何状态值,强制更新一下</button>
                    </div>
                )
            }
            add = ()=>{
                const {count} = this.state
                this.setState({count:count+1})
            }
            //卸载组件按钮的回调
            die = ()=>{
                ReactDOM.unmountComponentAtNode(document.getElementById("test"))
            }
            force = ()=>{
                this.forceUpdate();
            }
        }
        ReactDOM.render(<Count/>,document.getElementById("test"))

父子组件的调用:

class Parent extends React.Component{
            //初始化状态值
            state = {carName:"宝马"}
            //更换车
            changeCar = () =>{
                this.setState({carName:"奥拓"})
            }
            render(){
                return (
                    <div>
                         <h1>我是父组件</h1>
                         <button onClick={this.changeCar}>换车</button>
                         <Child carName={this.state.carName} />
                    </div>
                )
            }
        }
        class Child extends React.Component{
            //componentWillReceiveProps 第一次接收 属性值 不执行
            componentWillReceiveProps(props){
                console.log("子组件",'componentWillReceiveProps',props);
            }
            shouldComponentUpdate(){
                console.log("是否Ok",'shouldComponentUpdate');
                return true;
            }
            componentWillUpdate(){
                console.log("子组件",'compoentWillUpdate');
            }
            componentDidUpdate(){
                console.log("子组件","componentDidUpdate");
            }
            render(){
                console.log('子组件渲染');
                return (
                    <div>
                        我是子组件,接收到汽车是 {this.props.carName}
                    </div>
                )
            }
        }
        ReactDOM.render(<Parent/>, document.getElementById("test"))

新版本的生命周期

生命周期图(新).png

class Count extends React.Component{
            state = {count:0}
            //生命周期函数 挂载时如下
            //1, constructor(构造器)
            //2, componentWillMount(组件将要挂载)
            //构造器
            constructor(props){
                console.log("Count---constructor");
                super(props)
            }
           
            //组件挂载完毕的钩子
            componentDidMount(){
                console.log("Count---componentDidMount");
            }
           
            componentWillUnmount(){
                console.log("Count---componentWillUnmount");
            }

            //组件是否应该更新(true---go,false---stop) 默认返回true
            shouldComponentUpdate(){
                console.log("Count---shouleComponentUpdate");
                return true
                //如果是false, 就不再往下走了
            }
            //派生的状态:不是从state得到,是从props得到
            //此方法适用于罕见的用例,即 state 的值在任何时候都取决于 props, 可以使用此方法,但也可以完全不使用,即从地球上消失,没有作用
            static getDerivedStateFromProps(props,state){
                console.log("getDerivedStateFromProps",props,state);
               
                //this.setState({count:props.count})
               // return props
               return null
            }
            //组件更新完毕
            componentDidUpdate(preProps,preState,snapShot){
                console.log("Count---componentDidUpdate",preProps,preState,snapShot);
            }
          //getSnapshotBeforeUpdate (信息状态在更新之前来个快照)
          //同样,此用法很不常见
            getSnapshotBeforeUpdate(){
                console.log("更新快照","getSnapshotBeforeUpate");
                //快照值: 任何值都可以做为快照值 字符串,数组,对象
                return "庄子" //想传什么就传什么,传给componentDidUpdate
            }
            render(){
                console.log("Count---render");
                return (
                    <div>
                        <h1>当前的统计总数为: {this.state.count}</h1>
                        <button onClick={this.add}>点击+1</button>
                        <button onClick={this.die}>卸载组件</button>
                        <button onClick={this.force}>不更改任何状态值,强制更新一下</button>
                    </div>
                )
            }
            add = ()=>{
                const {count} = this.state
                this.setState({count:count+1})
            }
            //卸载组件按钮的回调
            die = ()=>{
                ReactDOM.unmountComponentAtNode(document.getElementById("test"))
            }
            force = ()=>{
                this.forceUpdate();
            }
        }
        //ReactDOM.render(<Count count = {10}/>,document.getElementById("test"))
        const e = React.createElement;
        const domContainer = document.querySelector('#test');
        const root = ReactDOM.createRoot(domContainer);
              root.render(e(Count));

1. 初始化阶段: 由ReactDOM.render()触发--初次渲染

         1. constructor()

         2. componentWillMount

         3. render()

         4. componentDidMount() =====> 常用

            一般在这个钩子中做一些初始化的事, 例如:开启定时器,发送网络请求,订阅信息

2. 更新阶段: 由组件内部this.setState()或父组件render触发

         1. shouldComponentUpdate()

         2. componentWillUpdate()

         3. render() =====> 必须使用的一个

         4. componentDidUpdate()

3. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发

         1. componentWillUnmount()  ===> 常用

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


新的生命周期:

        即将废弃:componentWillMount,componentWillUpdate(),componentWillReceiveProps

        增加:

        getDervedStatefrorProps(得到派生的状态从props),

        getsrapchotEeloreUpdate

        (以上两个用法极其罕见, 即使完全不会也没有关系)


<