React 生命周期

116 阅读4分钟

react 生命周期17版本

constuctor:(组件初始化)

1. 组件的初始化,用来定义当前组件所需要的一些状态,状态定义在this.state中。
2. 当前组件必须书写super方法,接入props,否则在次生命周期中将访问不到props属性,

componentWillMount: (挂载前) 此生命周期已经被移除

1. 可以进行数据请求,应用于服务端渲染
2. 可以在数据第一次被渲染的时候做数据的更改
3. 当前生命周期尽量不要使用 ** this.setState **,因为当前生命周期执行完毕会自动执行render函数
4. 可以将外部数据转换为内部数据

render: (渲染DOM,数据与模板结合)

1.render 函数第一次执行会将渲染的数据在内存中保存一份,当数据发生改变,
	render将会这次的虚拟DOM和缓存的虚拟DOM进行对比,这叫DIFF算法,
2.只要this.state或this.props中的数据发生变化,就会触发render函数

componentDidMount: (挂载后)

1. 当前生命周期我们可以做前后端数据的交互
2. 可以在当前生命周期获取到真实DOM,获取方式通过 this.refs 进行获取
3. 一般情况我们在当前生命周期做一些插件的实例化:
	例如: new Swiper('')
    操作真实DOM的方式:
    	ref = 'h2'   this.refs.h2
        ref ={ (el) => {this.dom = el} } this.dom
     

componentWillReceiveProps(newProps): (this.props改变触发当前生命周期) 此生命周期已被移除

1. 当前生命周期会有一个参数,这个参数为新的porps
2. 当前生命周期中我们可以对新的props进行修改

shouldComponentUpdate(newPorps, newState): (当this.porps // this.state 被修改时触发)

1. 当前生命周期执行时必须 return truefalse,返回值决定了render函数是否会执行,
2. 当前生命周期为React 性能优化节点,可根据新旧的props/state进行比较来决定是否执行render函数
3. 当前生命周期默认的两个参数分别为更新后的props与state
4. 当前生命周期只是决定render函数是否执行,与数据修改无关,

componentWillUpdate(newProps, newState): (数据更新前) 此生命周期已被移除

 1. 当前生命周期我们可以对更新的数据做最后的修改,
 2. 当前生命周期两个参数分别为更新的props与state

componentDidUpdate: (更新后)

 1. 当前生命周期我们可以获取到数据更新后最新的DOM结构,
 2. 当前生命周期会被执行多次,书写业务逻辑需要做一定判断

componentWillUnmount: (卸载)

 1. 当前生命周期可以做事件解绑,数据移除等销毁类操作
 

总结: 在第一次渲染时执行生命周期有:

	Constructor;
	componentWillMount;
	render;
	componentDidMount

当this.props/ this.state 发生改变执行执行生命周期有:

this.props 改变:
	componentWillReceiveProps
    shouldComponentUpdate
    componentWillUpdate
    render
    componentDidUpdate
 this.state 改变:
 	shouldComponentUpdate
    componentWillUpdate
    render
    componentDidUpdate
  

有哪些生命周期 会执行一次,哪些会执行多次:

	多次执行:
   		componentWillReceiveProps;
   		shouldComponentUpdate;
   		componentWillUpdate
   		render;
   		componentDidUpdate
	一次执行:
    		constructor;
        	componentWillMount;
        	componentDidMount
    		componentWillUnmount

在17版本废除生命周期有(componentWillMount,componentwillReceiveProps,componentWillUpdate), 增加生命周期有:

getDerivedStateFromProps(nextProps, prevState): 根据传入的props更新state

	1. 该方法是一个 static 方法意味着这个方法是属于 React.Component 类的方法,所以方法内是无法使用 this 的,这就意味着无法使用 this.setState 来更新 state,所以这个方法直接通过返回对象的形式来更新 state,如果某些 props 的情况不需要更新 state,那么就返回 null 就好。实际上这个方法和 componentDidUpdate 搭配使用,就能覆盖 componentWillReceiveProps 的所有使用场景了
    
	static getDerivedStateFromProps(nextProps, prevState) {
    	if ( nextProps.pos !== prevState.pos) {
        	return {
            	pos: nextPorps.pos
            }
        }
        return null
    }

getSnapshotBeforeUpdate:

  1. 在更新之前获取组件的快照,在组件更新前触发

  2. 它的返回值作为第三个参数传递给后面的componentDidUpdate 参数中,和commentDidUpdate 一起使用,能够覆盖commentWillUpdate 的所有使用场景,

componendDidCatch(error, info):

如果组件定义了commentDidcatch 生命周期,它将成为一个错误边界(错误边界会捕捉渲染期间,在生命周期方法中和它们之下整棵树的构造函数中的错误,就像使用了try catch ,不会将错误直接抛出,保证了应用的可用性)

参考: www.cnblogs.com/rkpbk/p/110…