diff --git a/src/App.tsx b/src/App.tsx index 27d7d32..c45d60e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -2,6 +2,7 @@ import { useState } from 'react'; import MainMenu from './components/menu/MainMenu'; import GameView from './components/game/GameView'; import ReplayView from './components/replay/ReplayView'; +import ErrorBoundary from './components/common/ErrorBoundary'; import './App.css'; type Page = 'menu' | 'game' | 'replay'; @@ -13,15 +14,21 @@ function App() { const handleReplayStart = () => setPage('replay'); const handleBackToMenu = () => setPage('menu'); - if (page === 'game') return ; - if (page === 'replay') return ; + let content: React.ReactNode; + if (page === 'game') { + content = ; + } else if (page === 'replay') { + content = ; + } else { + content = ( + + ); + } - return ( - - ); + return {content}; } export default App; diff --git a/src/components/common/ErrorBoundary.tsx b/src/components/common/ErrorBoundary.tsx new file mode 100644 index 0000000..c9410cb --- /dev/null +++ b/src/components/common/ErrorBoundary.tsx @@ -0,0 +1,62 @@ +import { Component, type ReactNode } from 'react'; + +interface Props { + children: ReactNode; +} + +interface State { + hasError: boolean; + error: Error | null; +} + +export default class ErrorBoundary extends Component { + constructor(props: Props) { + super(props); + this.state = { hasError: false, error: null }; + } + + static getDerivedStateFromError(error: Error): State { + return { hasError: true, error }; + } + + render() { + if (this.state.hasError) { + return ( +
+

程序出错了

+
+            {this.state.error?.message}
+          
+ +
+ ); + } + return this.props.children; + } +}