React生命周期

代码银月使
• 阅读 2100

React生命周期

react可以将页面分成一个一个独立或嵌套的组件,使得整体代码可复用性特别高;react组件的挂载到销毁的过程中有七个生命周期钩子函数,可以在不同的生命周期函数中写业务逻辑代码

componentWillMount

组件将要被挂载,这个阶段发生在组件render函数之前,初始化state状态之后

componentDidMount

组件已经挂载完成,这个阶段发生在render函数执行之后,是组件首次创建完成后的最终形态

componentWillReceiveProps

组件将要接收新的属性,这个阶段发生在组件的属性改变的时候,并且是组件重新渲染的过程中第一个执行的方法

shouldComponentUpdate

组件是否要更新,这个阶段发生在componentWillReceiveProps之后,控制组件是否会重新渲染,唯一一个需要返回值的钩子函数

componentWillUpdate

组件将要更新,这个阶段发生在shouldComponentUpdate之后,render函数执行之前

componentWillUnmount

组件将要被销毁,当组件由于功能需求或者用户操作,需要卸载的时候执行此钩子函数,一般用于解除组件的定时器或者事件监听函数

代码示例

//定义一个时钟组件
class Clock extends Component {

    constructor(){
        super();
        this.state={
            time: new Date().toLocaleString()
        };
    }

    componentWillReceiveProps(){
        console.log("clock receive props");
    }

    shouldComponentUpdate(){
        console.log("clock should update");
        return true;
    }

    componentWillUpdate(){
        console.log("clock will update");
    }

    componentDidUpdate(){
        console.log("clock did update");
    }

    componentWillMount(){
        console.log("clock will mount");
    }

    componentDidMount(){
        console.log("clock did mount");
        this.timer=setTimeout(()=>{
            this.setState({
                time: new Date().toLocaleString()
            });
        },1000);
    }

    componentWillUnmount(){
        console.log("clock unmount");
        clearInterval(this.timer);
    }

    render(){
        console.log("clock render");
        return (
          <div>
              {this.props.country }: {this.state.time}
          </div>
        )
    }
}

//在Index组件中使用Clock组件,并且将Index组件在页面中渲染出来
class Index extends Component {

    constructor(){
        super();
        this.state={
            isShow: true,
            country: "china"
        };
    }

    shouldComponentUpdate(){
        console.log("index should update");
        return true;
    }

    componentWillUpdate(){
        console.log("index will update");
    }

    componentDidUpdate(){
        console.log("index did update");
    }

    componentWillMount(){
        console.log("index will mount");
    }

    componentDidMount(){
        console.log("index did mount");
    }

    render(){
        console.log("index render");
        return (
          <div>
              {
                  this.state.isShow?
                      <Clock country={this.state.country} /> : null
              }
            <button onClick={()=>{this.setState({isShow: !this.state.isShow})}}>
                {
                    this.state.isShow?"hide":"show"
                }
            </button>
              {
                  this.state.isShow?
                      <button onClick={()=>{this.setState({country: this.state.country==="china"?"usa":"china"})}}>transform</button> : null
              }
          </div>
        )
    }
}

页面首次被渲染的时候依次在控制台打印出如下结果:

  • index will mount

  • index render

  • clock will mount

  • clock render

  • clock did mount

  • index did mount

紧接着,一秒过后,定时器中的函数执行,对Clock组件的状态进行了修改,于是浏览器依次输出如下结果:

  • clock should update

  • clock will update

  • clock render

  • clock did update

从上面可以看出update类型的钩子函数只会在组件存在之后状态改变时执行。之后点击transform按钮,将Clock接收的props中的country属性改变成usa,浏览器输出如下结果:

  • index should update

  • index will update

  • index render

  • clock receive props

  • clock should update

  • clock will update

  • clock render

  • clock did update

  • index did update

再点击hide按钮,使Clock组件从页面中卸载,浏览器输出如下结果:

  • index should update

  • index will update

  • index render

  • clock unmount

  • index did update

以上就是react组件完整的生命周期,每个react组件从创建到销毁都会经历如此过程,这些生命周期钩子能够帮助我们实现项目中各种各样的功能需求。

点赞
收藏
评论区
推荐文章
海军 海军
4年前
React Hook丨用好这9个钩子,所向披靡
ReactHook指南什么是Hook?Hook是React16.8的新增特性。它可以让你在不编写class的情况下使用state以及其他的React特性。Hook本质上就是一个函数,它简洁了组件,有自己的状态管理,生命周期管理,状态共享。useStateuseEffectuseContextus
郜小超 郜小超
4年前
史上最全前端面试题(但是没有答案 自己百度 手动狗头!)
Vue面试题生命周期函数面试题1.什么是vue生命周期2.vue生命周期的作用是什么3.第一次页面加载会触发哪几个钩子4.简述每个周期具体适合哪些场景5.created和mounted的区别6.vue获取数据在哪个周期函数7.请详细说下你对vue生命周期的理解?vue路由面试题1.mvvm框架是什么?2.vuerout
Souleigh ✨ Souleigh ✨
4年前
React - 认识生命周期
这周开始学习React的生命周期。React的生命周期从广义上分为三个阶段:挂载、渲染、卸载.挂载卸载过程constructor()componentWillMount()componentDidMount()componentWillUnmount()更新过程componentWillRece
爱丽丝13 爱丽丝13
4年前
快速了解 React Hooks 原理
为了保证的可读性,本文采用意译而非直译。我们大部分React类组件可以保存状态,而函数组件不能?并且类组件具有生命周期,而函数组件却不能?React早期版本,类组件可以通过继承PureComponent来优化一些不必要的渲染,相对于函数组件,React官网没有提供对应的方法来缓存函数组件以减少一些不必要的渲染,直接16.6出来的Rea
Souleigh ✨ Souleigh ✨
4年前
React 灵魂 23 问,你能答对几个?
1、setState是异步还是同步?1.合成事件中是异步2.钩子函数中的是异步3.原生事件中是同步4.setTimeout中是同步相关链接:你真的理解setState吗?:2、聊聊react@16.4的生命周期相关连接:React生命周期我对Reactv16.4生命周期的
Stella981 Stella981
3年前
React Native 中组件的生命周期
概述就像Android开发中的View一样,ReactNative(RN)中的组件也有生命周期(Lifecycle)。所谓生命周期,就是一个对象从开始生成到最后消亡所经历的状态,理解生命周期,是合理开发的关键。RN组件的生命周期整理如下图:!33componentlifecycle(https://static.osch
Stella981 Stella981
3年前
React知识杂烩(持续更新)
每隔半年不看官方文档,你就会不认识React了😁React组件生命周期受控组件与非受控组件多个输入的解决方法Props.children可以传递任何数据包括函数布尔值、Null和Undefined被忽略使用PropTypes进行类型检查(直接参考官方文档)reactredux
Stella981 Stella981
3年前
React 新特性 React Hooks 的使用
关注前端技术专栏,回复“资源”免费领取全套视频教程正文什么是Hooks?Hooks是React16.8的新增特性。它可以让你在不编写class的情况下使用state以及其他的React特性。是一些可以让你在函数组件里“钩入”Reactstate及生命周期等特性的函数。Ho
提升前端开发效率的五种实用技术
组件化开发是一种将页面拆分成独立的可重用组件的开发方式。通过组件化开发,我们能够将复杂的界面逻辑拆分成独立的模块,提高代码的复用性和维护性。常用的组件化框架如React、Vue和Angular,它们提供了强大的组件化开发能力,使我们能够轻松构建复杂的用户界面,并提供了组件的生命周期管理和状态管理机制。
融云IM即时通讯 融云IM即时通讯
6个月前
融云IM干货丨uni-app 生命周期有哪些?
uniapp的生命周期分为应用生命周期、页面生命周期和组件生命周期三类:应用生命周期应用生命周期函数需要在App.vue中声明,主要包含以下函数:onLaunch:当uniapp初始化完成时触发(全局只触发一次)。onShow:当uniapp启动,或从后台
代码银月使
代码银月使
Lv1
不要在深夜里做任何决定,睡一觉吧,明天醒来再说。
文章
3
粉丝
0
获赞
0