錯誤邊界
- React16增加
- 防止某個組件的UI渲染錯誤導致整個應用崩潰
- 子組件發生JS錯誤,有備用的渲染UI
- 錯誤邊界是組件,只能用class組件來寫
錯誤邊界組件捕獲錯誤的時機
- 渲染時
- 生命周期函數中
- 組件樹的構造函數中
getDerivedStateFromError
- 生命周期函數 static getDerivedStateFromError(error)
- 參數:子組件拋出的錯誤
- 返回值:新的state
- 渲染階段調用
- 作用:不允許出現副作用(異步代碼、操作dom等)
componentDidCatch
- 生命周期函數
- 組件原型上的方法
- 邊界組件捕獲異常,并進行后續處理
- 作用:錯誤信息獲取,運行副作用
- 在組件拋出錯誤后調用
- 參數:error(拋出的錯誤)、info(組件引發錯誤相關的信息,即組件棧)
componentDidCatch(err, info) {console.log('componentDidCatch err', err)console.log('componentDidCatch info', info)
}
無法捕獲的場景
- 1.事件處理函數(無法顯示備用UI)
function Correct() {const handleClick = () => {console.log('點擊')throw new Error('click throw err')}return (<div onClick={handleClick}>正常顯示內容</div>)
}
<ErrorBoundary><Correct />
</ErrorBoundary>
- 2.異步 setTimeout、ajax
function Correct() {const err = () => {setTimeout(() => {throw new Error('拋出錯誤')}, 1000)}err()return (<div>正常顯示內容</div>)
}
<ErrorBoundary><Correct />
</ErrorBoundary>
- 3.服務端渲染
- 4.錯誤邊界組件(
ErrorBoundary
)內部有錯誤
class ErrorBoundary extends React.Component {state = {hasError: false,}static getDerivedStateFromError() {return {hasError: true}}render() {if (this.state.hasError) {return (<h1>This is Error UI{data}</h1>)}return this.props.children}
}
<ErrorBoundary><TestErr />
</ErrorBoundary>
以上幾種情況有可能導致整個React組件被卸載
示例代碼
class ErrorBoundary extends React.Component {state = {hasError: false,}static getDerivedStateFromError() {return {hasError: true}}render() {if (this.state.hasError) {return (<h1>This is Error UI</h1>)}return this.props.children}
}
function TestErr() {return (<h1>{data}</h1>)
}
function Correct() {return (<div>正常顯示內容</div>)
}
function App() {return (<div><ErrorBoundary><TestErr /></ErrorBoundary><Correct /></div>)
}
ReactDOM.render(<App />,document.getElementById('app')
)
錯誤邊界組件能向上冒泡
TestErr
有錯誤,冒泡到ErrorBoundary
,ErrorBoundary
自身也有錯誤- 如果多個嵌套錯誤邊界組件 → 則從最里層錯誤觸發、向上冒泡觸發捕獲
<ErrorBoundary2><ErrorBoundary><TestErr /></ErrorBoundary>
</ErrorBoundary2>
- 在開發模式下,錯誤會冒泡至window,而生產模式下,錯誤不會冒泡,詳見文檔
class ErrorBoundary2 extends React.Component {constructor(props) {super(props)window.onerror = function (err) {console.log('window.onerror err', err)}}state = {hasError: false,}static getDerivedStateFromError(err) {return {hasError: true}}render() {if (this.state.hasError) {return (<h1>This is Error UI2</h1>)}return this.props.children}
}