React 生命周期鈎子函數詳解


一、回顧vue中的生命周期
    beforeCreate              created
    beforeMount              mounted    
    beforeUpdate             updated
    beforeDestroy            destroyed
    activated                    deactivated
二、react生命周期鈎子函數
    初始化階段
    constructor                                       初始化數據---初始化狀態
    componentWillMount                      以前建議進行ajax請求,最后一次修改狀態的機會,但是現在基本上都componentDidMount中請求
    render                                               第一次裝載(渲染)數據
    componentDidMount                       ajax請求,更新狀態,進入運行時階段,更新視圖,還可以實例化一些對象
    運行時階段
    componentWillReceiveProps            子組件接收到父組件的數據
    shouldComponentUpdate                本組件是不是需要進行去更新視圖,默認為true,要不不寫,寫了必寫返回值,false表示不更新視圖
    componentWillUpdate                     組件即將被更新-----無實際意義
    render                                                重新渲染數據
    componentDidUpdate                     實例化一些對象(特別是如果數據是動態請求的)
    銷毀
    componentWillUnmount                   清除一些計時器,定時器等
     錯誤異常處理
    componentDidCatch
componentDidCatch  --- 錯誤邊界作為 React 組件,用以捕獲在子組件樹中任何地方的 JavaScript 異常,打印這些錯誤,並展示備用 UI 而非讓組件樹崩潰。錯誤邊界會捕獲渲染期間,在生命周期方法中以及在其整個樹的構造函數中的異常。
 
簡單來說  就是使用異常的組件包裹App組件
<ErrorBoundary><App/></ErrorBoundary>
 
ErrorBoundary組件
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  componentDidCatch(error, info) {
    this.setState({ hasError: true });
  }
  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
 
 
 
 
 


免責聲明!

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



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