React组件生命周期过程说明

实例化

首次实例化

  • getDefaultProps
  • getInitialState
  • componentWillMount
  • render
  • componentDidMount

实例化完成后的更新

  • getInitialState
  • componentWillMount
  • render
  • componentDidMount

存在期

组件已存在时的状态改变

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

销毁&清理期

  • componentWillUnmount

说明

生命周期共提供了10个不同的API。

1.getDefaultProps

作用于组件类,只调用一次,返回对象用于设置默认的props,对于引用值,会在实例中共享。

var MyTitle = React.createClass({
  getDefaultProps : function () {
    return {
      title : 'Hello World'
    };
  },

  render: function() {
     return <h1> {this.props.title} </h1>;
   }
});

ReactDOM.render(
  <MyTitle />,
  document.body
);

输出结果:

"Hello World"

2.getInitialState

作用于组件的实例,在实例创建时调用一次,用于初始化每个实例的state,此时可以访问this.props。

3.componentWillMount

在完成首次渲染之前调用,此时仍可以修改组件的state。如果在这个方法内调用setState,render() 将会感知到更新后的state,将会执行仅一次,尽管 state 改变了。

4.render

必选的方法,创建虚拟DOM,该方法具有特殊的规则:

  • 只能通过this.props和this.state访问数据
  • 可以返回null、false或任何React组件
  • 只能出现一个顶级组件(不能返回数组)
  • 不能改变组件的状态
  • 不能修改DOM的输出

5.componentDidMount

真实的DOM被渲染出来后调用,在该方法中可通过this.getDOMNode()访问到真实的DOM元素。此时已可以使用其他类库来操作这个DOM。在服务端中,该方法不会被调用。

6.componentWillReceiveProps

componentWillReceiveProps(object nextProps)

在组件接收到新的props 的时候调用。在初始化渲染的时候,该方法不会调用。

用此函数可以作为react 在 prop 传入之后, render() 渲染之前更新 state 的机会。老的 props 可以通过 this.props 获取到。在该函数中调用 this.setState() 将不会引起第二次渲染。

componentWillReceiveProps:function(nextProps){
  this.setState({
    likesIncreasing: nextProps.likeCount> this.props.likeCount
  });
}

7.shouldComponentUpdate

shouldComponentUpdate(object nextProps, object nextState)

在接收到新的props 或者 state,将要渲染之前调用。该方法在初始化渲染的时候不会调用,在使用 forceUpdate 方法的时候也不会。

如果确定新的props 和 state 不会导致组件更新,则此处应该 返回 false。

shouldComponentUpdate:function(nextProps,nextState) {
  return nextProps.id!== this.props.id;
}

如果 shouldComponentUpdate 返回false,则 render() 将不会执行,直到下一次 state 改变。(另外,componentWillUpdate 和 componentDidUpdate 也不会被调用。)

默认情况下,shouldComponentUpdate 总会返回true,在 state 改变的时候避免细微的bug,但是如果总是小心地把 state 当做不可变的,在 render() 中只从 props 和state 读取值,此时你可以覆盖 shouldComponentUpdate 方法,实现新老 props 和state 的比对逻辑。

如果性能是个瓶颈,尤其是有几十个甚至上百个组件的时候,使用 shouldComponentUpdate可以提升应用的性能。

8.componentWillUpdate

componentWillUpdate(object nextProps, object nextState)

接收到新的props或者state后,进行渲染之前调用,此时不允许更新props或state。

9.componentDidUpdate

componentDidUpdate(object prevProps, object prevState)

完成渲染新的props或者state后调用,你仍然可以使用 this.getDOMNode() 来访问到新的DOM元素。

10.componentWillUnmount

组件被移除之前被调用,可以用于做一些清理工作,在componentDidMount方法中添加的所有任务都需要在该方法中撤销,比如创建的定时器或添加的事件监听器。或者清除在 componentDidMount 中创建的 DOM 元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值