错误边界
当一个页面包含N个组件时,其中一个组件报错,就会导致整个页面白屏,这并不是我们想要的
ErrorPage.jsx
import React, {Component} from 'react';
import ErrorView from "./ErrorView";
class ErrorPage extends Component {
render() {
return (
零零三
);
}
}
export default ErrorPage;
ErrorView.jsx
import React, {Component} from 'react';
class ErrorView extends Component {
state={
list: null
}
render() {
const {list} = this.state
return (
{list.map((item, index)=>{
return index={index}
})}
);
}
}
export default ErrorView;
错误页面的结果为
整个页面都是白屏
进行错误边界的处理ErrorBoundary.jsx
import React, {Component} from 'react';
class ErrorBoundary extends Component {
state = {
hasError: false,
error: null,
errorInfo: null
}
componentDidCatch(error, errorInfo) {
this.setState({
hasError: true,
error,
errorInfo
})
}
render() {
if (this.state.hasError){
return {this.props.render(this.state.error,this.state.errorInfo)}
}
return this.props.children;
}
}
export default ErrorBoundary;
ErrorView.jsx
import React, {Component} from 'react';
class ErrorView extends Component {
state={
list: null
}
render() {
const {list} = this.state
return (
{list.map((item, index)=>{
return index={index}
})}
);
}
}
export default ErrorView;
ErrorPage.jsx
import React, {Component} from 'react';
import ErrorView from "./ErrorView";
import ErrorBoundary from './ErrorBoundary'
class ErrorPage extends Component {
render() {
return (
零零三
组件发生了错误/error:{error.message}}>
);
}
}
export default ErrorPage;
结果
关掉错误弹窗
这样只会将发生该错误的组件展示错误信息,而不是整个页面白屏