React.js -- Component Lifecycle

Mounting

Component added to DOM

Method

  • componentDidMount(): doing initialization work that require DOM
    • e.g. add listener, fetch data from server

Updating

setState() is called or prop updated

Method

  • getSnapshotBeforeUpdate(): doing saving work
    • takes snapshot of current prop & state
  • componentDidUpdate(previousProps, previousState, snapshot): get current prop & state before updated
  • shouldComponentUpdate(newProps, newState): optimize update
    • e.g. compare with the current state and decide not to update the component

Unmounting

Component removed from DOM

Method

  • componentWillUnmount(): doing cleanup work
    • e.g. close stuff to prevent memory leak

Example

class TextAreaCounter extends React.Component {
  // ...

  componentDidMount() {
    console.log('componentDidMount');
  }
  componentWillUnmount() {
    console.log('componentWillUnmount');
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('componentDidUpdate     ', prevProps, prevState, snapshot);
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log('getSnapshotBeforeUpdate', prevProps, prevState);
    return 'hello';
  }
  shouldComponentUpdate(newProps, newState) {
    console.log('shouldComponentUpdate  ', newProps, newState);
    return true;
  }

  // ...
}

Order of method calling:

  1. componentDidMount(): start
  2. shouldComponentUpdate(): update comes in
  3. getSnapshotBeforeUpdate(): update will happen
  4. componentDidUpdate(): update done
  5. componentWillUnmount(): end

Update Checking

  • Implement incoming change checking logic in componentDidUpdate:
componentDidUpdate(prevProps, prevState) {
    
    // checking logic
    if(condition){
        this.setState({ xxx: this.props.xxx});
    } else{
        this.setState({ xxx: prevState.xxx});
    }

}
  • You can always use prevState/prevProps to revert back the update
  • If the update is valid, go ahead and set the value to this.props/this.state which is updated

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值