错误边界(Error Boundaries)
import React,{Component} from 'react';
class ErrorBoundary extends Component{
constructor(props){
super(props);
this.state = {
}
}
componentDidCatch(error,info){
this.setState({
error: error,
errorInfo: info
})
}
render(){
if(this.state.errorInfo){
return <h1>Something went wrong.</h1>
}
return this.props.children;
}
}
export default ErrorBoundary;
import React,{Component} from 'react';
import ErrorBoundary from './../../components/ErrorBoundary';
function Example(){
//throw new Error('I crashed!');
//return <div>Ex</div>
}
class ErrorExample extends Component{
render(){
return(
<ErrorBoundary>
<Example/>
</ErrorBoundary>
)
}
}
export default ErrorExample;
参考文章:https://www.jianshu.com/p/3ae9838ed51c
事件处理器如何处理?
class ErrorExample extends Component{
constructor(props){
super(props);
this.state = {
error: false
}
this.handleClick = this.handleClick.bind(this);
}
handleClick=()=>{
console.log('handleClick');
try {
// Do something that could throw
throw new Error();
} catch (error) {
this.setState({ error });
}
}
render(){
if(this.state.error){
return <h1>Caught an error.</h1>
}
return <div onClick={this.handleClick}>Click Me</div>
}
}
export default ErrorExample;