Vue 中的錯誤捕獲:
vue 中 errorCaptured 只能捕獲自己子組件的錯誤,如果子組件出錯了,父組件沒有處
理,就會一級一級往上, 如果 app組件還沒有處理,根組件也沒有處理,就會報錯。
但是不可能在每一個組件裏面都使用 errorCaptured 捕獲, 而且一個 app 裏面可能有
很多需要錯誤捕獲的地方, 所以建議在 app.vue 中 或者 根組件裏面處理
那 Vue 中如何處理異常?
- 顯示錯誤頁面(配置一個錯誤路由)
- 收集錯誤(錯誤信息,賬號信息,手機設備信息等),提交給後臺
示例代碼:
errorCaptured(error) {
console.log('root 出錯了');
console.log(error.message);
// 我們最多隻能拿到這個, 如果是在控制檯就可以用這樣
// 手機上可以用 android,ios會更清晰
console.log(window.navigator.userAgent);
return false; // 這樣就不會在控制檯打印了
}
React 中的錯誤捕獲:
只會在最外層處理 react 中的錯誤
react 中 index.js 中 render 是處理不了錯誤的,需要在 App.js 中處理
有兩個處理錯誤的方法: 二選一就好了
方法一:getDerivedStateFromError(靜態方法)
static getDerivedStateFromError(error) {
// 1.顯示錯誤提示界面
// 2.收集錯誤信息,提交給後臺
return {
isError: true;
}
// 這個 return 的值也會跟 state 進行合併
}
方法二:componentDidCatch(實例方法)
componentDidCatch(error) {
// 1.顯示錯誤提示界面
// 2.收集錯誤信息,提交給後臺
this.setState({
isError: true
})
}
兩個方法沒有誰優誰劣,只不是看你使用哪個方便就使用哪個
如果要使用 this 就使用了後面這個實例方法,靜態方法中this 指向類
通常錯誤不會寫在組件裏面,每個組件裏面的邏輯已經夠多了
而是單獨封裝個錯誤組件,在 index.js 裏面引入,包裹 App,
這個錯誤組件就是錯誤邊界
React 中 錯誤邊界組件的簡單實例代碼:
import React, { Component } from 'react'
export default class Error extends Component {
constructor(props) {
super(props);
this.state = {
isError: false
}
}
render() {
if(!this.state.isError){
//沒有錯
return this.props.children; // 組件包裹的結構
}else{
return (
<div>
出錯了
<button onClick={this.goHomeAction.bind(this)}>回到首頁</button>
</div>
)
}
}
goHomeAction(){
this.setState({isError: false}, ()=>{
//切換到首頁
})
}
componentDidCatch(){
this.setState({isError: true});
}
}
好啦,今天的錯誤捕獲就到這裏啦 ~