如何在使用react-router路由的组件中集成错误边界
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在使用react-router路由的组件中集成错误边界相关的知识,希望对你有一定的参考价值。
我有一个页面使用不同的组件,使用反应路由器加载。当我使用react路由器路由到不同的页面时,是否可以在每个组件中集成错误边界,如下面的代码所示?
我的目标是特别针对单个组件显示错误,以便在一个组件中出现错误时,其他组件应该可以正常工作。
请参阅下面的代码:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
App.js
import React, { Component } from 'react';
import {BrowserRouter as Router, Route, Link } from 'react-router-dom';
//import ErrorBoundary from "./errorboundary";
import MyComponent1 from './component1';
import MyComponent2 from './component2';
class App extends Component {
render() {
return (
<Router>
<div style={{ backgroundColor: 'green' }}>
<div style={{ backgroundColor: '#f0f0ae', height: '30px' }}>
<Link to='/'>Link 1</Link>   
<Link to='/comp1'>Link 2</Link>   
<Link to='/comp2'>Link 3</Link>   
</div>
<div style={{ backgroundColor: '#ffc993', height: '150px' }}>
<Route path='/' exact render={() => <MyComponent1 title="Component 1" />} />
<Route path='/comp1' render={() => <MyComponent1 title="Component 1 Again" />} />
<Route path='/comp2' render={() => <MyComponent2 title="Component 2" />} />
</div>
</div>
</Router>
);
}
}
export default App;
这是我想要使用Error Boundary的组件之一。
component1.js
import React, { Component } from 'react';
import ErrorBoundary from "./errorboundary";
class MyComponent1 extends Component {
state = {
boom: false,
};
throwError = () => this.setState({ boom: true });
render() {
const { title } = this.props;
if(this.state.boom) {
throw new Error(`${title} throw an error!`);
}
return (
<ErrorBoundary>
<input type='button' onClick={this.throwError} value={title} />
</ErrorBoundary>
)
}
}
export default MyComponent1;
这是我想要使用错误边界的另一个组件。
component2.js
import React, { Component } from 'react';
import ErrorBoundary from "./errorboundary";
class MyComponent2 extends Component {
state = {
boom: false,
};
throwError = () => this.setState({ boom: true });
render() {
const { title } = this.props;
if(this.state.boom) {
throw new Error(`${title} throw an error!`);
}
return (
<ErrorBoundary>
<input type='button' onClick={this.throwError} value={title} />
</ErrorBoundary>
)
}
}
export default MyComponent2;
当每个组件中存在错误时,这是我使用错误边界的自定义错误消息。
errorboundary.js
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
if(this.props.showError === false)
{
this.state.error = null;
this.state.errorInfo = null;
}
}
componentDidCatch = (error, info) => {
console.log("error did catch");
this.setState({error: error, errorInfo: info });
}
render() {
if(this.state.errorInfo) {
return (
<div style={{ backgroundColor: '#ffcc99', color: 'white', width: '500px', height: '60px' }}>
An Error Occurred !
</div>
);
}
else {
return this.props.children;
}
}
}
export default ErrorBoundary;
谁能帮帮我吗?我是React JS的新手。
答案
你没有在正确的地方使用ErrorBoundary
。在ErrorBoundary
标签周围包装input
只确保如果输入中有错误,那就是被ErrorBoundary
捕获
return (
<ErrorBoundary> {/* errorBounday here only catches error in input */}
<input type='button' onClick={this.throwError} value={title} />
</ErrorBoundary>
)
您需要将ErrorBoundary包装在引发错误的组件周围
<Route
path="/comp1"
render={() => (
<ErrorBoundary>
<MyComponent1 title="Component 1 Again" />
</ErrorBoundary>
)}
/>
这样,如果MyComponent1抛出一个错误,它就会被错误边界捕获,这就是你的情况。你的代码看起来像
class App extends React.Component {
render() {
return (
<Router>
<div style={{ backgroundColor: "green" }}>
<div style={{ backgroundColor: "#f0f0ae", height: "30px" }}>
<Link to="/">Link 1</Link>   
<Link to="/comp1">Link 2</Link>   
<Link to="/comp2">Link 3</Link>   
</div>
<div style={{ backgroundColor: "#ffc993", height: "150px" }}>
<Route
path="/"
exact
render={() => (
<ErrorBoundary>
<MyComponent1 title="Component 1" />
</ErrorBoundary>
)}
/>
<Route
path="/comp1"
render={() => (
<ErrorBoundary>
<MyComponent1 title="Component 1 Again" />
</ErrorBoundary>
)}
/>
<Route
path="/comp2"
render={() => (
<ErrorBoundary>
<MyComponent2 title="Component 2" />
</ErrorBoundary>
)}
/>
</div>
</div>
</Router>
);
}
}
请阅读understanding how to test ErrorBoundaries in codesandbox的这个问题
以上是关于如何在使用react-router路由的组件中集成错误边界的主要内容,如果未能解决你的问题,请参考以下文章