React 生命周期

学习React,生命周期很重要,我们了解完生命周期的各个组件,对写高性能组件会有很大的帮助.

React 生命周期分为三种状态 1. 初始化 2.更新 3.销毁 

React 生命周期

组件初始化时渲染之前 开始渲染渲染之后生命周期,当我们要修改组件时才会触发更新的生命周期,顺序依次为确认是否修改(true or false)修改之前开始渲染修改之后,最后为销毁的生命周期,在组件销毁时触发

React 生命周期

App.js组件

import React, { Component } from 'react';

//导入axios
import Life from "./Life";

class App extends Component {
  constructor(props){
    super(props)
    this.state={
      isshow:"true"
    }
  }
  showbtn=()=>{
  this.setState({
    isshow:!this.state.isshow
  })
  }
  render() {
    return (
      <div className="App">
       {
          this.state.isshow?<Life/>:""
        }
       <button onClick={this.showbtn}>isshow</button>
   
      </div>
    );
  }
}

export default App;

Life.js组件 

import React,{Component} from "react"
class Life extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            msg:"我是修改之前的值"
         };
    }
    //修改值
    setmsg=()=>{
       this.setState({
           msg:"我是修改之后的值"
       })
    }
        //继承了组件的生命周期----就是方法

    //渲染之前
    componentWillMount(){
        console.log("渲染之前");
    }
    
    //渲染完成之后
    componentDidMount(){
        console.log("渲染之后");
    }


    // 确认是否修改
    shouldComponentUpdate(){
        return true
    }

    //修改之前 
    componentWillUpdate(){
        console.log("修改之前")
    }
 
    //修改之后
    componentDidUpdate(){
        console.log("修改之后")
    }


    //卸载 生命周期
    componentWillUnmount(){
        console.log("卸载")
    }


    //props  的值放生改变的时候调用的
    componentWillReceiveProps(){        
    }

    //开始渲染
    render() {
        console.log("开始渲染")
        return (         
            <div>             
                Life
                <button onClick={this.setmsg}>开始修改值</button>
            </div>
        );
    }
}

export default Life;