生命周期是一个组件从建立到销毁的过程。react会在不一样的时间点注入相应的钩子函数,以便于开发者进行更灵活的数据处理。react
生命周期只存在于类组件中,函数组件没有生命周期。可是在后来的新版本react提供了hooks用于管理函数组件的状态。
constructor(props)
函数:ajax
setState
,页面还未挂载。componentWillMount
函数:数组
setState
,可是很容易致使bug,不建议在这里使用;render
函数:性能优化
setState
方法,会形成无限递归内存泄露。componentDidMount
函数:微信
componentWillReceiveProps(nextProps)
函数:dom
shouldComponentUpdate(nextProps, nextState)
函数:异步
true
执行render
函数,返回false
不执行render
函数;componentWillUpdate(nextProps, nextState)
函数:函数
componentDidUpdate(prevProps, prevState, snapshot)
函数:性能
componentWillUnmount()
函数:优化
官方图解已经画的很清楚了,这里不在赘述,主要说一下区别。
componentWillMount
函数
componentWillReceiveProps
函数
componentWillUpdate
函数
getDerivedStateFromProps(props, state)
函数
static
关键字;getSnapshotBeforeUpdate(prevProps, prevState)
函数
componentDidUpdate(prevProps, prevState, snapshot)
连用,返回的值做为该函数的第三个参数传入。setSate
在dom事件处理函数中调用时就是异步的;举个例子:
import React, {Component} from 'react' export default class index extends Component{ state = { count: 0 } //点击一次count加2 hanldeClick = () => { this.State({ count: this.state.count + 1 }) this.State({ count: this.state.count + 1 }) } render(){ return ( <div onClick={this.hanldeClick}>{this.state.count}</div> ) } }
根据上述代码,在点击div
以后,按道理,count
的值应该变成2
,但实际显示的确是1
。
解决办法:给setState
传入一个函数更新数据。
//点击一次count加2 hanldeClick = () => { //使用这种方式获取的上一个state是最新的 this.State(function(state, props) { return { count: state.count + 2 }; }) }
react团队以为,dom事件处理函数中状态处理会比较复杂,setState
的次数比较多,若是每次setState
就去更新页面,会影响页面渲染效率,因此会将事件中的多个setState
合并成同一个。