1. 程式人生 > >React 生命周期鉤子函數詳解

React 生命周期鉤子函數詳解

turn clas () 函數 ted dea truct tor stat

一、回顧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; } }

React 生命周期鉤子函數詳解