【发布时间】:2018-03-22 11:44:38
【问题描述】:
我正在尝试处理错误并在 react js 中记录错误
我使用 errorBoundary 方法处理错误,但它只支持 react js 版本 16
import React, {Component} from "react";
import "./App.css";
import errorimg from './errorimg.svg';
//create a erro boundry
class ErrorLimit extends Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
//set the error value when invoked
componentDidCatch(error, errorInfo) {
this.setState({
error: error,
errorInfo: errorInfo
})
logErrorToMyService(error, info);
}
render() {
//checked the error
if (!!this.state.errorInfo) {
return (
<div className="snap">
<img src= {errorimg}/>
<div className="snap-message">
{this.state.error && this.state.error.toString()}
{this.state.errorInfo.componentStack}
<p> <b>Error occured - something's gone wrong.</b></p>
<p>Anyway we handled error
</p>
</div>
</div>
);
} else {
return this.props.children;
}
}
}
class Widget extends Component {
constructor(props) {
super(props);
this.state = { loading: true, n: 0 };
this.getCount = this.getCount.bind(this)
}
getCount() {
if (this.state.n > 3) throw new Error('woops..counter betes limit');
return `(${this.state.n})`;
}
handleClick() {
this.setState({ n: this.state.n + 1 });
}
render() {
return (
<div>
<div>Counter widget {this.getCount(this.state.n)}</div>
<button onClick={this.handleClick.bind(this)}>
Click me a few times
</button>
</div>
);
}
}
class SampleApp extends Component {
render() {
return (
<div className="sidebar">
{/* here we used error boundry */}
<ErrorLimit>
<Widget />
</ErrorLimit>
</div>
);
}
}
class App extends Component {
render() {
return (
<div className="app">
<SampleApp />
</div>
);
}
}
export default App;
我已经尝试了另一种反应版本 15 的方法,它工作正常。成功处理错误但无法记录错误
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import wrapWithTryCatch from 'react-try-catch-render';
import errorimg from './errorimg.svg';
class MyErrorHandler extends React.Component {
render(){
return (
<div className="App-header">{this.props.error}</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { loading: true, n: 0 };
this.getCount = this.getCount.bind(this)
this.handleClick = this.handleClick.bind(this);
}
getCount() {
if (this.state.n > 3) throw new Error('woops..counter betes limit');
return `(${this.state.n})`;
}
handleClick() {
this.setState({ n: this.state.n + 1 });
}
render(){
return(
<div>
<div>Counter widget {this.getCount(this.state.n)}</div>
<button onClick={this.handleClick.bind(this)}>
Click me a few times
</button>
</div>
);
}
}
export default wrapWithTryCatch(React, MyErrorHandler, {error: "Error catched!"})(App);
请任何人提出一种方法来处理错误并在反应版本 15 中记录错误
【问题讨论】:
-
你可以在构造函数中试试这个:
this.state = { hasError: false };,在componentDidCatch中:this.setState({ hasError: true });,然后在渲染测试中if (this.state.hasError) {?
标签: reactjs error-handling error-logging