若是将React的生命周期比喻成一只蚂蚁爬过一根吊绳,那么这只蚂蚁从绳头爬到绳尾,就会依次触动不一样的卡片挂钩。在React每个生命周期中,也有相似卡片挂钩的存在,咱们把它称之为‘钩子函数’。那么在React的生命周期中,到底有哪些钩子函数?React的生命周期又是怎样的流程?今天我给你们来总结总结react
如图,React生命周期主要包括三个阶段:初始化阶段、运行中阶段和销毁阶段,在React不一样的生命周期里,会依次触发不一样的钩子函数,下面咱们就来详细介绍一下React的生命周期函数算法
static defaultProps = { name: 'sls', age:23 }; //or Counter.defaltProps={name:'sls'} 复制代码
constructor() { super(); this.state = {number: 0} } 复制代码
组件即将被渲染到页面以前触发,此时能够进行开启定时器、向服务器发送请求等操做数组
组件渲染bash
组件已经被渲染到页面中后触发:此时页面中有了真正的DOM的元素,能够进行DOM相关的操做服务器
组件接收到属性时触发markdown
当组件接收到新属性,或者组件的状态发生改变时触发。组件首次渲染时并不会触发dom
shouldComponentUpdate(newProps, newState) { if (newProps.number < 5) return true; return false } //该钩子函数能够接收到两个参数,新的属性和状态,返回true/false来控制组件是否须要更新。 复制代码
通常咱们经过该函数来优化性能:函数
一个React项目须要更新一个小组件时,极可能须要父组件更新本身的状态。而一个父组件的从新更新会形成它旗下全部的子组件从新执行render()方法,造成新的虚拟DOM,再用diff算法对新旧虚拟DOM进行结构和属性的比较,决定组件是否须要从新渲染性能
无疑这样的操做会形成不少的性能浪费,因此咱们开发者能够根据项目的业务逻辑,在
shouldComponentUpdate()
中加入条件判断,从而优化性能测试
例如React中的就提供了一个
PureComponent
的类,当咱们的组件继承于它时,组件更新时就会默认先比较新旧属性和状态,从而决定组件是否更新。值得注意的是,PureComponent
进行的是浅比较,因此组件状态或属性改变时,都须要返回一个新的对象或数组
组件即将被更新时触发
组件被更新完成后触发。页面中产生了新的DOM的元素,能够进行DOM操做
组件被销毁时触发。这里咱们能够进行一些清理操做,例如清理定时器,取消Redux的订阅事件等等。
import React from 'react' import ReactDOM from 'react-dom'; class SubCounter extends React.Component { componentWillReceiveProps() { console.log('九、子组件将要接收到新属性'); } shouldComponentUpdate(newProps, newState) { console.log('十、子组件是否须要更新'); if (newProps.number < 5) return true; return false } componentWillUpdate() { console.log('十一、子组件将要更新'); } componentDidUpdate() { console.log('1三、子组件更新完成'); } componentWillUnmount() { console.log('1四、子组件将卸载'); } render() { console.log('十二、子组件挂载中'); return ( <p>{this.props.number}</p> ) } } class Counter extends React.Component { static defaultProps = { //一、加载默认属性 name: 'sls', age:23 }; constructor() { super(); //二、加载默认状态 this.state = {number: 0} } componentWillMount() { console.log('三、父组件挂载以前'); } componentDidMount() { console.log('五、父组件挂载完成'); } shouldComponentUpdate(newProps, newState) { console.log('六、父组件是否须要更新'); if (newState.number<15) return true; return false } componentWillUpdate() { console.log('七、父组件将要更新'); } componentDidUpdate() { console.log('八、父组件更新完成'); } handleClick = () => { this.setState({ number: this.state.number + 1 }) }; render() { console.log('四、render(父组件挂载)'); return ( <div> <p>{this.state.number}</p> <button onClick={this.handleClick}>+</button> {this.state.number<10?<SubCounter number={this.state.number}/>:null} </div> ) } } ReactDOM.render(<Counter/>, document.getElementById('root')); 复制代码