錯誤邊界是一種特殊的組件,能夠用來捕獲並打印發生在其子組件樹任何位置
的JavaScript錯誤,並渲染出備用UI。
錯誤邊界會在渲染期間
,聲明週期方法
,和整組件樹的構造函數
中捕獲錯誤。因此錯誤邊界沒法捕獲如下場景中產生的錯誤:react
錯誤邊界相似於JavaScript的catch,可是它只針對react服務器
錯誤邊界能夠解決部分UI的JavaScript錯誤會致使整個應用崩潰的問題。
自 React 16 起,任何未被錯誤邊界捕獲的錯誤將會致使整個 React 組件樹被卸載,使用錯誤邊界能夠提供更好的用戶體驗異步
在class組件中定義static getDerivedStateFromError()
或componentDidCatch()
着兩個聲明週期方法中的任意一個(或兩個),該組件就成爲了一個錯誤邊界。函數
getDerivedStateFromError()
用來處理錯誤componentDidCatch()
來輸出完整的錯誤信息//定義 class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // 更新 state 使下一次渲染可以顯示降級後的 UI return { hasError: true }; } componentDidCatch(error, errorInfo) { // 你一樣能夠將錯誤日誌上報給服務器 logErrorToMyService(error, errorInfo); } render() { if (this.state.hasError) { // 你能夠自定義降級後的 UI 並渲染 return <h1>Something went wrong.</h1>; } return this.props.children; } } //使用 <ErrorBoundary> <MyWidget /> </ErrorBoundary>
錯誤邊界能夠搭配錯誤監控來記錄生產環境產生的錯誤this
在任意react組件外來包裹錯誤邊界,以保護邊界外的內容不崩潰spa
try / catch 僅能用於命令式代碼(imperative code),可是react組件是聲明式的,因此須要錯誤邊界來捕捉錯誤日誌