【React】生命周期函数

12 篇文章 0 订阅

在某一时段会自动执行的函数

 

Initialization初始化

constructo()中完成

Mounting 组件第一次挂载到页面的流程

componentWillMount :render之前    组建即将被挂载到页面上时执行

componentDidMount :render之后     组件挂载后执行

Updation 组件更新

shouldComponentUpdate  :给出一个布尔值判断是否更新组件

componentWillUpdate :确定更新组件,render前执行

componentDidUpdate :组件更新后,render后执行

componentWillReceiveProps:一般只有子组件会运行,但是在子组件还没挂载时不执行

Unmounting 

componentWillUnmount 组件除去挂载后执行

 

 

用处 

  • 父组件更新时子组件也会更新,但有时父组件更新时,子组件不需要更新,为了避免性能浪费,可以使用shouldComponentUpdate,判断子组件属性有没有变化,若没有变化则无需更新
	shouldComponentUpdate(nextProps, nextState) {
		if (nextProps.content !== this.props.content){
			return true;
		}
		else{
			return false;
		}
	}
  • 要使用ajax请求数据时,放在render里会导致循环,因为render是实时更新的,所以把ajax请求放在componentDidMount()里,要使用ajax请求 ,首先在项目目录中,控制台 输入
  • yarn add axios 安装 引用后就可以使用
import axios from 'axios'
	
    componentDidMount(){
		axios.get('/api/todolist')
		.then(()=>{alert('sucess')})
		.catch(()=>{alert('fail')})
		console.log('Todolist:componentDidMount')
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值