react生命周期函数 出场顺序-应用场景

生命周期函数图

在这里插入图片描述

生命周期函数应用场景

页面首次挂载

componentWillMount

在组件即将被挂载到页面的时刻自动执行,还没被挂载到页面,仅首次被挂载时被执行,输入之后不会执行
顺序:componentWillMount – render

componentDidMount

组件被挂载到页面之后自动执行,仅首次被挂载时被执行,输入之后不会执行
顺序:componentWillMount – render – componentDidMount

请求Ajax数据,不放在render函数是为了避免多次请求 — 最合理方式,就放在这里
在组件被挂载到页面上的时候会被请求,不会重复执行

componentDidMount () {
	{/* 生命周期函数, 初始化页面向后台请求数据 */}
	axios.get('/api/todolist')
		.then(() => 	{alert('succ')})
		.catch(() => 	{alert('error')})
}

render

组件被更新的时候,实时自动执行

组件被更新页面

componentWillReceiveProps

子组件特有执行,只有props有
一个组件要从父组件接收参数,只要父组件的render函数被执行了,子组件的这个生命周期函数就会被执行
如果这个组件第一次存在于父组件中,不会执行
如果这个组件之前已经存在于父组件中,才会执行

shouldComponentUpdate

组件被更新之前,会被执行
顺序:shouldComponentUpdate(false) – render

放在子组件,返回false,不必时刻渲染,增强子组件的性能, nextProps, nextState接下来可能会变成什么样, 只有值变更过才渲染,避免过多的render的操作,减少创建虚拟dom的比对

shouldComponentUpdate (nextProps, nextState) {
	if (nextProps.content !== this.props.content) {
		return true;
	} else {
		return false;
	}
}

componentWillUpdate

组件被更新之前,会被执行
顺序:shouldComponentUpdate(true) – componentWillUpdate – render

componentDidUpdate

组件被更新完成之后,会被执行
顺序:shouldComponentUpdate(true) – componentWillUpdate – render – componentDidUpdate

组件被剔除

componentWillUnmount

把组件从页面剔除的时候

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章