ReactJS语法-组件的生命周期、性能优化
概念
- 在组件创建、到加载到页面上运行、以及组件被销毁的过程中,总是伴随着各种各样的事件,这些在组件特定时期,触发的事件,统称为 组件的生命周期;

组件创建阶段
组件创建阶段的生命周期函数,有一个显著的特点:创建阶段的生命周期函数,在组件的一辈子中,只执行一次;
- componentWillMount: 组件将要被挂载,此时还没有开始渲染虚拟DOM
- render:第一次开始渲染真正的虚拟DOM,当render执行完,内存中就有了完整的虚拟DOM了
- componentDidMount: 组件完成了挂载,此时,组件已经显示到了页面上,当这个方法执行完,组件就进入都了 运行中 的状态
组件运行阶段
也有一个显著的特点,根据组件的state和props的改变,有选择性的触发0次或多次;
- componentWillReceiveProps: 组件将要接收新属性,此时,只要这个方法被触发,就证明父组件为当前子组件传递了新的属性值;
- shouldComponentUpdate: 组件是否需要被更新,此时,组件尚未被更新,但是,state 和 props 肯定是最新的
- componentWillUpdate: 组件将要被更新,此时,尚未开始更新,内存中的虚拟DOM树还是旧的
- render: 此时,又要重新根据最新的 state 和 props 重新渲染一棵内存中的 虚拟DOM树,当 render 调用完毕,内存中的旧DOM树,已经被新DOM树替换了!此时页面还是旧的
- componentDidUpdate: 此时,页面又被重新渲染了,state 和 虚拟DOM 和 页面已经完全保持同步
组件销毁阶段
也有一个显著的特点,一辈子只执行一次;
- componentWillUnmount: 组件将要被卸载,此时组件还可以正常使用;
组件生命周期函数
-
React生命周期的回调函数总结成表格如下:

-
组件生命周期的执行顺序:
- Mounting:
- constructor()
- componentWillMount()
- render()
- componentDidMount()
- Updating:
- componentWillReceiveProps(nextProps)
- shouldComponentUpdate(nextProps, nextState)
- componentWillUpdate(nextProps, nextState)
- render()
- componentDidUpdate(prevProps, prevState)
- Unmounting:
- componentWillUnmount()
Counter计数器案例
defaultProps设置组件默认值
- 在组件创建之前,会先初始化默认的props属性,这是全局调用一次,严格地来说,这不是组件的生命周期的一部分。在组件被创建并加载候,首先调用 constructor 构造器中的 this.state = {},来初始化组件的状态。
-
创建Counter.jsx
import React from 'react' export default class Counter extends React.Component { constructor(props) { super(props) // 初始化组件的私有状态,保存的是组件的私有数据 this.state = { msg: 'ok' } } // 在封装一个组件的时候,组件内部,肯定有一些数据是必须的,哪怕用户没有传递一些相关的启动参数,这时候,组件内部 ,尽量 给自己提供一个默认值; // 在 React 中,使用静态的 defaultProps 属性,来设置 组件的 默认属性值; static defaultProps = { initcount: 0 // 如果外界没有传递 initcount,那么,自己初始化一个 数值,为0 } render() { return <div> <h1>这是 Counter 计数器组件</h1> <input type="button" value="+1"/> <hr /> <h3 id="myh3">当前的数量是:{this.props.initcount}</h3> </div> } } -
main.js导入
import React from 'react' import ReactDOM from 'react-dom' import Counter from './components/Counter.jsx' // 使用 render 函数渲染 虚拟DOM ReactDOM.render(<div> <Counter></Counter> {/*胡乱传递数据,这就需要组件内部做数据类型校验 */} <Counter initcount="哈哈哈哈哈"></Counter> </div>, document.getElementById('app')) -
index.html
<body> <!-- 容器,将来通过 React 渲染得到的 虚拟DOM,会呈现到这个位置 --> <div id="app"></div> </body>
propTypes实现组件内部数据类型校验
-
如果外部给Counter组价传递的是垃圾数据,那么组件内部就需要做类型校验
//main.js ... {/*胡乱传递数据,这就需要组件内部做数据类型校验 */} <Counter initcount="哈哈哈哈哈"></Counter> ... -
Counter.jsx内部新增propTypes
- 添加第三方包,叫做 prop-types
- 导入
// 注意: prop-types 包中职能跟单一,只提供了 一些常见的 数据类型,用于做类型校验 import ReactTypes from 'prop-types' export default class Counter extends React.Component { ... // 这是创建一个 静态的 propTypes 对象,在这个对象中,可以把 外界传递过来的属性,做类型校验; // 注意: 如果要为 传递过来的属性做类型校验,必须安装 React 提供的 第三方包,叫做 prop-types ; // prop-types 大概在 v.15.* 之前,并没有单独抽离出来,那时候,还和 react 包 在一起;后来, 从 v.15.* 之后,官方把类型校验的 模块,单独抽离为 一个包,就叫做 prop-types static propTypes = { initcount: ReactTypes.number // 使用 prop-types 包,来定义 initcount 为 number 类型 } ... }
生命周期函数componentWillMount(废弃)
-
在Counter.jsx的render方法前面,添加componentWillMount方法
// 在组件即将挂载到页面上的时候执行,此时,组件尚未挂载到页面中 // 虚拟DOM是否创建好了呢?此时,内存中的虚拟DOM也没开始创建呢 componentWillMount() { // 此时,无法获取到 页面上的 任何元素,因为 虚拟DOM 和 页面 都还没有开始渲染呢!【在这个阶段中,不能去操作页面上的DOM元素】 // console.log(document.getElementById('myh3')); //可以获取到 // console.log(this.props.initcount); //可以获取到 // console.log(this.state.msg); //可以获取到 // this.myselfFunc() } //自定义方法 myselfFunc() { console.log('这是我自己定义的函数,和生命周期函数无关'); }
生命周期函数render
// 当执行到 这个 生命周期函数的时候,即将要开始渲染内存中的 虚拟DOM了,当这个函数执行完,内存中就有了一个 渲染好的虚拟DOM,但是,页面上尚未真正显示DOM元素呢;
render() {
// 在 return 之前,虚拟DOM还没有开始创建,页面上也是空的,根本拿不到任何的 元素
// console.log(document.getElementById('myh3'));
return <div>
<h1>这是 Counter 计数器组件</h1>
<input type="button" value="+1" id="btn"/>
<hr />
<h3 id="myh3">当前的数量是:{this.props.initcount}</h3>
</div>
// 当 return 执行完毕后, 虚拟DOM创建好了,但是,还没有挂载到真正的页面中
}
生命周期函数componentDidMount
- 在render函数下面新增componentDidMount。
- 官方建议在这里发送网络请求。
// 当组件挂载到页面上之后,会进入这个生命周期函数,只要进入这个生命周期函数了,必然说明,页面上,已经有可见的DOM元素了
// 当组件执行完 componentDidMount 函数后,就进入到了 运行中的状态,所以,componentDidMount 是创建阶段的最后一个函数
componentDidMount() {
// 在这个函数中,我们可以放心的去 操作 页面上你需要使用的 DOM 元素了;
// 如果我们想操作DOM元素,最早,只能在 componentDidMount 中进行;
// componentDidMount 相当于 Vue 中的 mounted 函数
// console.log(document.getElementById('myh3'));
}
生命周期函数shouldComponentUpdate
设置触发条件
-
给button添加点击事件,在componentDidMount中
componentDidMount() { document.getElementById('btn').onclick = () => { // console.log('ok'); // console.log(this); //initcount只读属性,不能改变,因此要使用state私有属性 // this.props.initcount++ //可以使用setState变更 this.setState({ count: this.state.count + 1 }) } } -
设置私有属性state接收外部参数
this.state = { msg: 'ok', count: props.initcount // 基数, 把 外界传递过来的 initcount 赋值给 state 中的 count值,这样,就把 count 值改成了可读可写的 state 属性,今后,就能实现 点击 按钮 ,count 值 + 1 的需求了 } -
将render中的h3标签的展示由props换成state
<h3 id="myh3" ref="h3">当前的数量是:{this.state.count}</h3> -
也可以通过react方式给buttn添加时间,不通过componentDidMount内部添加
//render中buttn添加点击事件 <input type="button" value="+1" id="btn" onClick={this.increment} /> //实现点击事件 increment = () => { this.setState({ count: this.state.count + 1 }) } -
以上当点击buttn时,就会改变私有属性state,就会触发组件页面更新,即shouldComponentUpdate
shouldComponentUpdate
// 从这里开始,就进入到了组件的运行中状态
// 判断组件是否需要更新
shouldComponentUpdate(nextProps, nextState) {
// 1. 在 shouldComponentUpdate 中要求必须返回一个布尔值
// 2. 在 shouldComponentUpdate 中,如果返回的值是 false,则 不会继续执行后续的生命周期函数,而是直接退回到了 运行中 的状态,此时有序 后续的 render 函数并没有被调用,因此,页面不会被更新,但是, 组件的 state 状态,却被修改了;
// return false
// 需求: 如果 state 中的 count 值是偶数,则 更新页面,如果 count 值 是奇数,则不更新页面,我们想要的页面效果:4,6,8,10,12....
// 经过打印测试发现,在 shouldComponentUpdate 中,通过 this.state.count 拿到的值,是上一次的旧数据,并不是当前最新的;
// console.log(this.state.count + ' ---- ' + nextState.count);
// return this.state.count % 2 === 0 ? true : false
//使用nextState获取最新值
// return nextState.count % 2 === 0 ? true : false
return true
}
生命周期函数componentWillUpdate
// 组件将要更新,此时尚未更新,在进入这个 生命周期函数的时候,内存中的虚拟DOM是旧的,页面上的 DOM 元素 也是旧的
componentWillUpdate() {
// 经过打印分析,得到,此时页面上的 DOM 节点,都是旧的,应该慎重操作,因为你可能操作的是旧DOM
// console.log(document.getElementById('myh3').innerHTML)
//1. 给h3标签绑定ref属性<h3 id="myh3" ref="h3">当前的数量是:{this.state.count}</h3>
//2. 使用refs来获取
// console.log(this.refs.h3.innerHTML);
// console.log(this.refs.h3.innerHTML);
}
生命周期函数componentDidUpdate
// 组件完成了更新,此时,state 中的数据、虚拟DOM、页面上的DOM,都是最新的,此时,你可以放心大胆的去操作页面了
componentDidUpdate() {
// console.log(this.refs.h3.innerHTML);
}
注意点
-
不要在 render 中使用 this.setState,因为 会陷入死循环
render() { //会陷入死循环 /* this.setState({ count: this.state.count + 1 }) */ return <div> <h1>这是 Counter 计数器组件</h1> <input type="button" value="+1" id="btn" onClick={this.increment} /> <hr /> <h3 id="myh3" ref="h3">当前的数量是:{this.state.count}</h3> </div> }
生命周期函数componentWillReceiveProps
- 理论上来说props属性是只读属性,那么如何设置props呗修改的场景呢?
- props属性只是在组件内部不能修改,但是可以在外部被修改。
- 场景:
- 设置一个父组件Parent和一个子组件Son
- 让父组件的state作为子组件Son的props传参。
- 点击父组件按钮变更state,那么子组件的props就变更了
-
创建父子组件TestReceiveProps.jsx
import React from 'react' // 父组件 export default class Parent extends React.Component { constructor(props) { super(props) this.state = { msg: '这是父组件中的 msg 消息' } } render() { return <div> <h1>这是父组件</h1> <input type="button" value="点击修改父组件的 MSG" onClick={this.changeMsg} /> <hr /> <Son pmsg={this.state.msg}></Son> </div> } changeMsg = () => { this.setState({ msg: '娃哈哈' }) } } // 子组件 class Son extends React.Component { constructor(props) { super(props) this.state = {} } render() { return <div> <h3>这是子组件 --- {this.props.pmsg}</h3> </div> } // 组件将要接收外界传递过来的新的 props 属性值 // 当子组件第一次被渲染到页面上的时候,不会触发这个 函数; // 只有当 父组件中,通过 某些 事件,重新修改了 传递给 子组件的 props 数据之后,才会触发 componentWillReceiveProps componentWillReceiveProps(nextProps) { // console.log('被触发了!'); // 注意: 在 componentWillReceiveProps 被触发的时候,如果我们使用 this.props 来获取属性值,这个属性值,不是最新的,是上一次的旧属性值 // 如果想要获取最新的属性值,需要通过 componentWillReceiveProps 的参数列表来获取 console.log(this.props.pmsg + ' ---- ' + nextProps.pmsg); } } -
main.js导入
import Test from './components/TestReceiveProps.jsx' //render中渲染 ReactDOM.render(<div> <Test></Test> </div>, document.getElementById('app'))
组件的性能优化
PureComponent
- shouldComponentUpdate方法可以用来性能优化,通常只要调用setState方法,或者外部传递给当前组件props,就会调用render,即使tate、props的数据没有变动,也会调用render进行重新渲染
- 那么在这个方法中,可以通过判断this.state与nextState、this.props 与nextProps的数据是否发生改变,来进行返回false或者true,从而来提升性能
- 如果所有的类,都需要手动来实现 shouldComponentUpdate,那么会给开发者增加非常多的工作量。因此Rect针对此问题提供了一个组件,叫PureComponent
如何使用PureComponent
- 将组件由React.Component继承自PureComponent即可。
- 该组件内部自动做了判断
export default class Parent extends React.PureComponent{
...
}
注意事项
-
不能直接修改原来的state,否则不会触发render
//1.直接修改原有的state,再重新设置一遍 //在Purecomponent是不能引入重新渲染(re-render) //this.state.books.push(newBook) //this.setstate({books:this.state.books}) //2.赋值一份books,·在新的books 中修改,设置新的books //深拷贝 const books =[...this.state.books]; books.push(newBook) this.setstate({ books:books })
函数是组件性能优化
- 函数式组件没有生命周期方法,只要外部传递props,那么就会重新渲染,那么如何进行优化呢?
- 通过memo来实现优化,把函数式组件用memo(包裹)生成一个新的组件
-
使用方法如下:
//函数式组件Profile import {memo }from "react" const Profile = memo( function(props){ console.log("profile render") return <h2>Profile:{props.message}</h2> } ) export default Profile //外部组件引用 <Profile message={message}/>- 效果:只有message值发生了变化,Profile组件才会被重新渲染