错误边界
当一个页面包含N个组件时,其中一个组件报错,就会导致整个页面白屏,这并不是我们想要的
ErrorPage.jsx
import React, {Component} from 'react';
import ErrorView from "./ErrorView";
class ErrorPage extends Component {
render() {
return (
<div>
<h1>零零三</h1>
<ErrorView/>
</div>
);
}
}
export default ErrorPage;
ErrorView.jsx
import React, {Component} from 'react';
class ErrorView extends Component {
state={
list: null
}
render() {
const {list} = this.state
return (
<div>
{list.map((item, index)=>{
return <p key={index}>index={index}</p>
})}
</div>
);
}
}
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 <div>{this.props.render(this.state.error,this.state.errorInfo)}</div>
}
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 (
<div>
{list.map((item, index)=>{
return <p key={index}>index={index}</p>
})}
</div>
);
}
}
export default ErrorView;
ErrorPage.jsx
import React, {Component} from 'react';
import ErrorView from "./ErrorView";
import ErrorBoundary from './ErrorBoundary'
class ErrorPage extends Component {
render() {
return (
<div>
<h1>零零三</h1>
<ErrorBoundary render={(error, errorInfo)=><p>组件发生了错误/error:{error.message}</p>}>
<ErrorView/>
</ErrorBoundary>
</div>
);
}
}
export default ErrorPage;
关掉错误弹窗
这样只会将发生该错误的组件展示错误信息,而不是整个页面白屏