React 生命周期

生命周期函数指在某一时刻组件会自动调用执行的函数

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

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

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

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;

生命周期函数的使用场景

1.提升性能,避免组件进行无用的render操作

当父组件内容改变时,避免子组件一直进行无用的render操作

  shouldComponentUpdate(nextProps,nextState){
        if(nextProps.content!== this.props.content){
            return true
        }else{
            return false
        }

    }
  render() {
        const {content}=this.props;
        console.log("render")
        return (
          
            <div onClick={this.handleClick}>{content}</div>
        );
    }

2.发送ajax请求,只渲染一次

componentDidMount(){}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值