文章目录
- 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;
`