react新的生命周期


一. react16當前生命周期

  • componentWillMount
    render前,所以setState不會重新渲染,服務端渲染唯一調用,推薦用constructor代替之
  • render
  • componentDidMount
    render后,調用setState會重新渲染,頁面可交互,可以請求數據
  • componentWillRecieveProps(nextProps)
    已掛載組件接收到新props觸發
  • shouldComponentUpdate(nextProps, nextState)
    在接收到新的props或state時是否重新渲染,默認返回true;首次渲染或forceUpdate時不會觸發;
  • componentWillUpdate(nextProps, nextState)
    如果shouldComponentUpdate返回false,update相關的函數都不會觸發;不要使用setState;
  • componentDidUpdate(nextProps, nextState)
  • componentWillUnmount
    卸載組件

二. 由於未來采用異步渲染機制,所以即將在17版本中去掉的生命周期鈎子函數

  • componentWillMount
  • componentWillRecieveProps
  • componentWIllUpdate

三. 新增兩個

  • static getDerivedStateFromProps
    會在初始化和update時觸發,用於替換componentWillReceiveProps,可以用來控制 props 更新 state 的過程;它返回一個對象表示新的 state;如果不需要更新,返回 null 即可
  • getSnapshotBeforeUpdate
    用於替換 componentWillUpdate,該函數會在update后 DOM 更新前被調用,用於讀取最新的 DOM 數據,返回值將作為 componentDidUpdate 的第三個參數

四. 建議用法

class A extends React.Component {
  // 用於初始化 state
  constructor() {}
  // 用於替換 `componentWillReceiveProps` ,該函數會在初始化和 `update` 時被調用
  // 因為該函數是靜態函數,所以取不到 `this`
  // 如果需要對比 `prevProps` 需要單獨在 `state` 中維護
  static getDerivedStateFromProps(nextProps, prevState) {}
  // 判斷是否需要更新組件,多用於組件性能優化
  shouldComponentUpdate(nextProps, nextState) {}
  // 組件掛載后調用
  // 可以在該函數中進行請求或者訂閱
  componentDidMount() {}
  // 用於獲得最新的 DOM 數據
  getSnapshotBeforeUpdate() {}
  // 組件即將銷毀
  // 可以在此處移除訂閱,定時器等等
  componentWillUnmount() {}
  // 組件銷毀后調用
  componentDidUnMount() {}
  // 組件更新后調用
  componentDidUpdate() {}
  // 渲染組件函數
  render() {}
  // 以下函數不建議使用
  UNSAFE_componentWillMount() {}
  UNSAFE_componentWillUpdate(nextProps, nextState) {}
  UNSAFE_componentWillReceiveProps(nextProps) {}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM