如何在使用react-router路由的组件中集成错误边界

时间:2018-03-06 12:28:57

标签: reactjs react-router

我有一个页面,它使用使用react路由器加载的不同组件。 当我使用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> &#160;&#160;
<Link to='/comp1'>Link 2</Link> &#160;&#160;
<Link to='/comp2'>Link 3</Link> &#160;&#160;
</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的新手。

3 个答案:

答案 0 :(得分:7)

ErrorBoundary包住您的主要路由器出口,但要为key提供唯一的ErrorBoundary,以迫使其拆除并在位置更改时构建新实例:

export const AppRouter = () => {
  const location = useLocation();

  return (
    <main>
      <ErrorBoundary key={location.pathname}>
        <Switch>
          <Route path="/" component={Dashboard} />
          <Route path="/orders" component={Orders} />
        </Switch>
      </ErrorBoundary>
    </main>
  );
};

请注意,只要位置更改,此简单但懒惰的解决方案都会导致ErrorBoundary中所有内容的不必要渲染。您可以通过基于路径名而不是使用整个路径名本身来计算频率变化较小的键来解决此问题。

答案 1 :(得分:6)

您没有在正确的地方使用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> &#160;&#160;
            <Link to="/comp1">Link 2</Link> &#160;&#160;
            <Link to="/comp2">Link 3</Link> &#160;&#160;
          </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>
    );
  }
}

DEMO

请阅读understanding how to test ErrorBoundaries in codesandbox

的这个问题

答案 2 :(得分:1)

我认为@Shubham Khatri的this answer是正确的,我只是想通过提供一个封装将<Route>包裹在<ErrorBoundary>中的逻辑的组件来完成它

const RouteWithErrorBoundary = (props) => {
    return (
        <ErrorBoundary key={props.location?.pathname}>
            <Route {...props} />
        </ErrorBoundary>
    );
};

让我们用打字稿添加一些类型:

const RouteWithErrorBoundary: React.FC<RouteProps> = (props) => {
    return (
        <ErrorBoundary key={props.location?.pathname}>
            <Route {...props} />
        </ErrorBoundary>
    );
};

您可以轻松地使用它:

<Switch>
    <RouteWithErrorBoundary path='/' exact render={() => <MyComponent1 title="Component 1" />} />
    <RouteWithErrorBoundary path='/comp1' render={() => <MyComponent1 title="Component 1 Again" />} />
    <RouteWithErrorBoundary path='/comp2' render={() => <MyComponent2 title="Component 2" />} />
</Switch>