Skip to content
This repository has been archived by the owner on Jun 17, 2023. It is now read-only.

Commit

Permalink
feat: error boundary wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
Lmmmmmm-bb committed Aug 3, 2022
1 parent 75447f6 commit 59bcd55
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
44 changes: 44 additions & 0 deletions components/error-boundary/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Component, PropsWithChildren } from 'react';
import { NavigateFunction, useNavigate } from 'react-router-dom';

type ErrorBoundaryPropsType = PropsWithChildren<{
navigator: NavigateFunction;
}>;

interface IErrorBoundaryState {
hasError: boolean;
}

class ErrorBoundary extends Component<
ErrorBoundaryPropsType,
IErrorBoundaryState
> {
constructor(props) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(_: Error) {
return { hasError: true };
}

render() {
return this.state.hasError ? (
<div style={{ width: 400, padding: 16, textAlign: 'center' }}>
<p>bviewer has something wrong.</p>
<button className='basic-btn' onClick={() => this.props.navigator('/')}>
返回主页
</button>
</div>
) : (
this.props.children
);
}
}

const ErrorBoundaryWithRouter =
(ClassComponent: typeof ErrorBoundary) =>
(props: Pick<ErrorBoundaryPropsType, 'children'>) =>
<ClassComponent navigator={useNavigate()}>{props.children}</ClassComponent>;

export default ErrorBoundaryWithRouter(ErrorBoundary);
13 changes: 10 additions & 3 deletions layouts/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import type { FC } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Route, Routes } from 'react-router-dom';
import ErrorBoundary from '~components/error-boundary';
import Follow from './follow';
import UpSpace from './up-space';

const WrapperErrorBoundary = (FunctionComponent: FC) => (
<ErrorBoundary>
<FunctionComponent />
</ErrorBoundary>
);

export const Router: FC = () => (
<Routes>
<Route path='/' element={<Follow />} />
<Route path='/up/:uid' element={<UpSpace />} />
<Route path='/' element={WrapperErrorBoundary(Follow)} />
<Route path='/up/:uid' element={WrapperErrorBoundary(UpSpace)} />
</Routes>
);

0 comments on commit 59bcd55

Please sign in to comment.