react的生命周期需要知道的。

 

有关React生命周期:

1、组件生命周期的执行次数是什么样子的???

复制代码
   只执行一次: constructor、componentWillMount、componentDidMount    执行多次:render 、子组件的componentWillReceiveProps、componentWillUpdate、componentDidUpdate    有条件的执行:componentWillUnmount(页面离开,组件销毁时)    不执行的:根组件(ReactDOM.render在DOM上的组件)的componentWillReceiveProps(因为压根没有父组件给传递props)
复制代码

 

2、组件的生命周期执行顺序是什么样子的???

  假设组件嵌套关系是  App里有parent组件,parent组件有child组件。

     如果不涉及到setState更新,第一次渲染的顺序如下:

复制代码
App:   constructor --> componentWillMount -->  render -->  parent: constructor --> componentWillMount -->  render -->  child:    constructor --> componentWillMount -->  render  -->  componentDidMount (child) -->  componentDidMount (parent) --> componentDidMount (App)
复制代码

 

   这时候触发App的setState事件

复制代码
App:   componentWillUpdate --> render -->  parent: componentWillReceiveProps --> componentWillUpdate --> render -->  child:    componentWillReceiveProps --> componentWillUpdate --> render --> componentDidUpdate (child) -->  componentDidUpdate (parent) --> componentDidUpdate (App)
复制代码

 

那如果是触发parent的setState呢?

复制代码
parent: componentWillUpdate --> render -->  child:     componentWillReceiveProps --> componentWillUpdate --> render -->  componentDidUpdate (child) -->  componentDidUpdate (parent) 
复制代码

 

那如果是只是触发了child组件自身的setState呢?

child: componentWillUpdate --> render -->  componentDidUpdate (child)

 

结论

1、如图:完成前的顺序是从根部到子部,完成时时从子部到根部。(类似于事件机制)

2、每个组件的红线(包括初次和更新)生命周期时一股脑执行完毕以后再执行低一级别的红线生命周期。

3、第一级别的组件setState是不能触发其父组件的生命周期更新函数,只能触发更低一级别的生命周期更新函数

 

总结起来就如下图:

 

 提问:那么这里提一个问题,如果App里面有多个parent1 parent2 ...,parent里由多个child,那么生命周期执行顺序应该时什么样的????

结论:一套组件(父包括子,子包括孙)执行的时候一个整体,执行完毕在执行下一套,用到这里就是App里先执行parent1和parent1的子,子的子。。。,然后完毕再执行parent2这一套。

 

 3、什么时候该用componentWillReceiveProps?

    是否每个子组件都需要componentWillReceiveProps生命周期函数来更新数据吗? 你的原则是??

 

A、开始前首先需要知道componentWillReceiveProps函数有一个参数nextProps,它是一个 { 对象 } ,从单词就可以看出它是update时候(也就是下一次)父组件传递过来的props

B、还要知道 "第一条中" 所讲解的有些生命周期函数只执行一次,而有的执行多次,其中componentWillReceiveProps执行多次,而constructor等执行一次

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信