我尝试使用错误边界来处理应用程序中的错误,但是由于某些原因,抛出错误时未调用componentDidCatch。我已经将react documentation中的应用简化为示例,但仍然无法正常工作。
我的反应版本是16.6.3。
ErrorHandler.js
import React from 'react';
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error, errorInfo) {
console.log('catch called')
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}
render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}
IndexPage.js
import React from 'react';
export default class IndexPage extends React.Component
{
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(({counter}) => ({
counter: counter + 1
}));
}
render() {
if (this.state.counter === 5) {
// Simulate a JS error
throw new Error('I crashed!');
}
return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
}
};
app.js
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from './AppRoutes';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import { loadState, saveState } from './localStorage';
import throttle from 'lodash/throttle';
import { createStore, compose, applyMiddleware } from 'redux';
import RootReducer from './reducers/flightControlApp';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { getMuiTheme } from 'material-ui/styles';
import IndexPage from './components/IndexPage';
import ErrorHandler from './components/ErrorHandler';
const middlewares = [];
middlewares.push(thunkMiddleware);
console.log("Running in DEBUG: " + DEBUG);
if (DEBUG)
{
const { logger } = require(`redux-logger`);
middlewares.push(logger);
// tests
//
// require('./UniTests/Test');
}
const persistedState = loadState();
let store = compose(applyMiddleware(...middlewares)) (createStore) (
RootReducer,
persistedState
);
if (DEBUG)
{
if (persistedState != undefined)
{
console.log('Initial state loaded: ');
console.log(persistedState);
}
}
store.subscribe(throttle(()=> {
saveState(store.getState());
}, 1000));
window.onload = () =>
{
ReactDOM.render(
<MuiThemeProvider muiTheme={getMuiTheme()}>
<ErrorHandler>
<IndexPage></IndexPage>
</ErrorHandler>
</MuiThemeProvider>,
document.getElementById('app'));
}
更新
引发异常时,UI不会崩溃,我仍然可以单击点击时增加的计数器,但是在控制台中,我看到: