大厂面经 ----- 详解react 16之前的生命周期(附带完整demo)

8 篇文章 0 订阅
1 篇文章 0 订阅
1. 父子组件的生命周期执行过程
1.1 首次渲染的过程
父constructor => 父componentWillMount => 父render => 
遇到子组件进入子组件的生命周期 => 子constructor => 
子componentWillMount => 子render => 
子componentDidMount => 父componentDidMount
1.2 数据更新

数据更新主要是通过两个生命周期函数:componentWillReceiveProps和shouldComponentUpdate。这里可以思考一个问题:demo里面当点击div时,传递给子组件的值变化。当我们不做任何处理的时候,子组件无法获取到父组件值的变化,那子组件怎么感应到父组件的值变化从而自动更新呢?

1.2.1 componentWillReceiveProps

这个生命周期主要是当父组件中改变了props传值时触发的函数,可以来使子组件随父组件自动更新。父组件re-render也会导致其子组件走更新流程(不管此时父组件传给子组件的props有没有改变),这种方式则是要走componentWillReceiveProps这步的。

1.2.2 shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState):可以通过这个方法控制组件是否重新渲染。如果返回 false 组件就不会重新渲染。这个生命周期在 React.js 性能优化上非常有用。

2. 面试过程中可能出现的问题
2.1 react中有什么生命周期,怎么执行的?

执行一次的生命周期函数:constructor,componentWillMount,componentDidMount ,componentDidUnMount 。
多次执行的函数:render,componentWillReceiveProps,shouldComponentUpdate

2.2 父组件中包含子组件,在渲染的时候,它们生命周期执行的顺序?

答案:首次渲染中的描述

2.3 在父组件传递给子组件数据时候,如果父类传递的props更新的时候,子类自动更新?
  1. 采用componentWillReceiveProps,可以把父类的props属性赋值给子类的state, 然后在componentWillReceiveProps执行的时候判断,如果props更新了,则执行setSate更新相应的state.
// 父类
render(){
	return (
	<div>
		<div onClick={() => this.handleClick('count')}>点我count{this.state.count}</div>
		<div onClick={() => this.handleClick('num')}>点我num{this.state.num}</div>
		<Child count={this.state.count}></Child>
	</div>
	)
}
// 子类
componentWillReceiveProps(nextProps){
		console.log('父组件传递的值')
		if(this.props.count !== nextProps.count){
			console.log(this.props.count)
			this.setState({
				childCount: nextProps.count
			})
		}
        
    }
    render(){
        console.log('03子数据渲染render')
        return (
			<div>{this.state.childCount}</div>
        )
    }

  1. shouldComponentUpdate好像做不到???
2.4 在父组件re-render时候,默认情况下,自组件是不是一定会re-render。

是的,一定会,不管从父类获得的props有无变化,其实这里子类不需要更新,这就需要优化,这就需要在子组件中增加shouldComponentUpdate, 判断props是否发生变化,如果没有变化就返回false,不需要更新。

// 父类
render(){
	return (
	<div>
		<div onClick={() => this.handleClick('count')}>点我count{this.state.count}</div>
		<div onClick={() => this.handleClick('num')}>点我num{this.state.num}</div>
		<Child count={this.state.count}></Child>
	</div>
	)
}
// 子类
// 
shouldComponentUpdate(nextProps,nextState){
	console.log('01子组件是否要更新数据')
	if(this.props.count === nextProps.count){
		return false
	}
	return true
render(){
       console.log('03子数据渲染render')
      return (
		<div>{this.state.childCount}</div>
       )
 }

demo地址:lifeCycle15

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值