react组件的生命周期

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cherry_zhang18/article/details/76976085
componentWillMount(): Fired once, before initial rendering occurs. Good place to 

wire-up message listeners. this.setState doesn't work here.


组件将要被挂载:在初始化render之前触发一次,并且永远只触发一次。this.setState不能工作


componentDidMount(): Fired once, after initial rendering occurs. Can use 

this.getDOMNode().


组件被挂载:在最初的渲染发生一次,在这个时候之后组件已经生成了对应的DOM结构,可以使用
this.getDOMNode(),可以在这个方法中执行setTimeout,setInterval或者发送AJAX请求等操作(

防止异部操作阻塞UI)。


componentWillUpdate(object nextProps, object nextState): Fired after the 

component's updates are made to the DOM. Can use this.getDOMNode() for updates.


组件将要被更新:在组件更新产生dom节点发生,可以使用this.getDOMNode()更新。
componentDidUpdate(object prevProps, object prevState): Invoked immediately after 

the component's updates are flushed to the DOM. This method is not called for the 
initial render. Use this as an opportunity to operate on the DOM when the component 

has been updated.


组件正在更新:组件更新刷新到DOM后立即调用。此方法不被调用在初始渲染。在组件更新时,将此

用作操作DOM的机会。


componentWillUnmount(): Fired immediately before a component is unmounted from the 

DOM. Good place to remove message listeners or general clean up.


组件将不被挂载:组件从dom树上在卸载之前发生,可以移除事件监听和处理。


componentWillReceiveProps(object nextProps): Fired when a component is receiving 

new props. You might want to this.setState depending on the props.


组件将要接收属性:当组件接收新的属性时,你会依靠这个属性来setState


shouldComponentUpdate(object nextProps, object nextState): Fired before rendering 
when new props or state are received. return false if you know an update isn't 

needed.


组件应该更新:当新的属性或者状态被接收到时发生,更新不是必须的就返回false.

组件的生命周期分成三个状态:

  • Mounting:已插入真实 DOM
  • Updating:正在被重新渲染
  • Unmounting:已移出真实 DOM

React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。

  • componentWillMount()
  • componentDidMount()
  • componentWillUpdate(object nextProps, object nextState)
  • componentDidUpdate(object prevProps, object prevState)
  • componentWillUnmount()

此外,React 还提供两种特殊状态的处理函数。

  • componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
  • shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用

展开阅读全文
博主设置当前文章不允许评论。

没有更多推荐了,返回首页