React生命周期

React生命周期分为装载更新卸载异常捕获

装载(Mounting)

组件被插入到DOM中

  • getDefaultProps()
    声明默认的属性,ES6之前是这样
var Greeting = createReactClass({
  getDefaultProps: function() {
    return {
      name: 'Mary'
    };
  },

  // ...

});

ES6是这样

class Greeting extends React.Component {
  // ...
}

Greeting.defaultProps = {
  name: 'Mary'
};
  • getInitialState()
    初始化state,ES6是constructor()

  • componentWillMount()

  • render()

  • componentDidMount()
    客户端有这步,而服务端则没有

更新(Updating)

组件重新渲染以更新DOM(state或props变化触发)

  • componentWillReceiveProps(nextProps)
    state变化可能不会触发它,因为state变化不一定组件的props变化
    nextProps为新接收到的属性
  • shouldComponentUpdate()
    返回true才会触发下面的componentWillUpdate、render、componentDidUpdate函数,false则不会
  • componentWillUpdate()
  • render()
  • componentDidUpdate()

卸载(Unmounting)

  • componentWillUnmount()

异常捕获(Error handling)

  • componentDidCatch()

图表总结

生命周期 调用次数 能否使用 setSate()
getDefaultProps 1(全局调用一次)
getInitialState 1
componentWillMount 1
render >=1
componentDidMount 1
componentWillReceiveProps >=0
shouldComponentUpdate >=0
componentWillUpdate >=0
componentDidUpdate 1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 组件的生命周期方法分以下三个阶段。 Mounting当创建组件的实例并将其插入到DOM中时,将调用这些方法:con...
    _八神光_阅读 1,142评论 0 0
  • 又是一个老生常谈的内容,从ES6起已经开始使用class的方式去创建组件,这种创建方式上的变化也带来了写法和方法上...
    殷灬商阅读 468评论 0 1
  • react生命周期流程 1.初始化,首次render getDefaultProps()getDefaultPro...
    瘦人假噜噜阅读 858评论 0 6
  • 好比我们人除了短暂的生与死那一瞬之外,生命中剩下的时间都用在了每天活着的状态,对于React中的组件来讲,占其总生...
    YeLqgd阅读 10,571评论 0 7
  • 译自 React Component Lifecycle 每个组件都有若干生命周期函数。如函数名称所示,带有wil...
    KrisLeeSH阅读 583评论 0 0