文章目錄
- ErrorBoundary
- 目錄結構
- 環境
- 具體應用
- 預覽
ErrorBoundary
ErrorBoundary可以在任務子元件中捕獲js錯誤,隻需在根元件中定義一次,即可捕獲所有子元件的錯誤。
然有以下4種錯誤除外:
1、事件處理函數中使用try catch
2、異步函數(setTimeout)
3、服務端渲染
4、目前ErrorBoundary抛出的錯誤
目錄結構
|-src/App.js
|-----pages/error/index.js
|----------------/template/index.js
|-------------------------/style.js
環境
“react”: “^16.7.0”,
“react-router-dom”: “^4.3.1”,
“styled-components”: “^4.1.3”
具體應用
// App.js
import React, { Component } from 'react';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
class App extends Component {
render() {
return (
<>
<Router>
<ErrorBoundary>
<Switch>
<Route path='/errorBoundaryExample' component={ErrorBoundaryExample}></Route>
</Switch>
</ErrorBoundary>
</Router>
</>
);
}
}
export default App
// error/index.js
import React from 'react';
import ErrorTemplate from './template'
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error, errorInfo) {
this.setState({
error: error,
errorInfo: errorInfo
})
}
render() {
if (this.state.errorInfo) {
// 出錯
return <ErrorTemplate title="error" tip="糟糕,頁面出錯了!"/>
}
// 正常頁面,渲染子元件
return this.props.children;
}
}
export default ErrorBoundary
// template/index.js
import React from 'react'
import {
ErrorWrapper,
Container,
RowContainer,
ErrorLink,
Tip,
ReturnLink
} from './style'
import {Link} from 'react-router-dom'
class ErrorTemplate extends React.Component {
render() {
const {title, tip} = this.props
return (
<ErrorWrapper>
<Container>
<RowContainer>
<ErrorLink>{title}</ErrorLink>
<Tip>{tip}</Tip>
</RowContainer>
</Container>
<RowContainer>
<Link to="/">
<ReturnLink>傳回首頁</ReturnLink>
</Link>
</RowContainer>
</ErrorWrapper>
)
}
}
export default ErrorTemplate
// template/style.js
import styled from 'styled-components'
export const ErrorWrapper = styled.div``
export const Container = styled.div`
text-align: center;
padding-top: 60px;
`
export const RowContainer = styled.div`
text-align: center;
`
export const ErrorLink = styled.span`
font-size: 150px;
padding: 10px;
`
export const Tip = styled.h2`
font-size: 1.5rem;
line-height: 3rem;
margin-bottom: 10px;
`
export const ReturnLink = styled.a`
color: #636363;
`