React(四)生命周期

React每个组件都包含生命周期方法,这些方法会在特定的阶段进行调用,如下图

这里说的组件是指类组件

在这里插入图片描述

挂载时

constructor

组件进行实例化时会执行该构造函数,如果不进行state的初始化或事件的绑定也可以不实现

也就是使用了该组件就会调用

render

页面就行渲染就会调用

无论是初始化渲染还是因为stateprops发生了改变

componentDidMount

组件成功挂载到DOM树上时进行调用,可以在该周期函数中进行发送网络请求或添加订阅等一些操作

// App.jsx
import About from "./components/About"
import React, { Component } from "react"
class App extends Component {
  render() {
    return (
      <div>
        App
        <About />
      </div>
    )
  }
}
// About.jsx
import React, { Component } from "react"

class About extends Component {
  constructor() {
    super()
    console.log("constructor")
  }
  render() {
    console.log("render")
    return <h1>About</h1>
  }
  componentDidMount() {
    console.log("挂载完成")
  }
}
export default About

在这里插入图片描述

更新时

componentDidUpdate

组件发生更新时调用,首次渲染不会执行,在必要条件下也可以在该周期函数中发送网络请求

// App.jsx 同上
// About.jsx
import React, { Component } from "react"

class About extends Component {
  constructor() {
    super()
    this.state = {
      name: "sakurige",
    }
    console.log("constructor")
  }
  changeName() {
    this.setState({
      name: "羽苏",
    })
  }
  render() {
    const { name } = this.state
    console.log("render")
    return (
      <div>
        <h1>About {name}</h1>
        <button onClick={() => this.changeName()}>Change Name</button>
      </div>
    )
  }
  componentDidMount() {
    console.log("挂载完成")
  }
  componentDidUpdate() {
    console.log("更新完成")
  }
}
export default About

About.jsx中增加了一个state以及一个按钮用于改变state,在初始状态下,同样是constructor``render``componentDidMount进行了调用,可见componentDidUpdate在首次渲染是不会执行的
在这里插入图片描述
点击按钮更新数据,rendercomponentDidUpdate执行
在这里插入图片描述

卸载时

component­Will­Unmount

组件卸载前调用,可以在该会调中进行一些清理操作,如清理定时器,取消网络请求以及移除之前添加的订阅等

// App.jsx 添加一个移除展示 About的按钮
class App extends Component {
  constructor() {
    super()
    this.state = {
      isShow: true,
    }
  }
  changeShow() {
    this.setState({
      isShow: !this.state.isShow,
    })
  }
  render() {
    const { isShow } = this.state
    return (
      <div>
        App
         {/* 根据 isShow的值判断是否移除 About */}
        {isShow ? <About /> : ""}
        <button onClick={() => this.changeShow()}>show</button>
      </div>
    )
  }
}
// About.jsx 添加 component­Will­Unmount 函数
 componentWillUnmount() {
    console.log("将要被卸载了")
  }

初始化时效果同上,点击切换按钮时触发 componentWillUnmount
在这里插入图片描述

其他生命周期函数

shouldComponentUpdate

根据返回值判断组件是否应该更新,true则更新,false不更新。上面componentDidUpdate,在第一次变化之后,如果再点击按钮state是不会发生变化的,但是componentDidUpdate依旧会进行回调,这时候可以通过该函数来判断一下

shouldComponentUpdate(nextProps, nextStates) {
	// 比较下一个 state 与 这一次的state是否相同
    return nextStates.name !== this.state.name
  }

仅作为性能优化存在。不要依赖它来阻止渲染,也不建议深度检查,如果要进行相关优化建议使用内置的PureComponent

更多生命周期

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值