fix: 修复白屏 — SW networkFirst + initSession try/catch + Error Boundary
1. sw.js: /index.html 导航请求使用 networkFirst 策略替代 cacheFirst, 避免旧 SW 缓存不存在的旧 hash 资源导致 404 白屏 2. App.tsx: initSession 添加 try/catch 异常保护,防止初始化 失败导致整个 React 树崩溃 3. 新建 ErrorBoundary.tsx: React 错误边界组件,捕获渲染异常 显示友好错误页面而非白屏
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import React, { Component, ErrorInfo, ReactNode } from 'react'
|
||||
|
||||
interface Props {
|
||||
children: ReactNode
|
||||
fallback?: ReactNode
|
||||
}
|
||||
|
||||
interface State {
|
||||
hasError: boolean
|
||||
error: Error | null
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends Component<Props, State> {
|
||||
constructor(props: Props) {
|
||||
super(props)
|
||||
this.state = { hasError: false, error: null }
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: Error): State {
|
||||
return { hasError: true, error }
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
||||
console.error('[ErrorBoundary] Caught error:', error, errorInfo)
|
||||
}
|
||||
|
||||
handleReset = () => {
|
||||
this.setState({ hasError: false, error: null })
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
if (this.props.fallback) return this.props.fallback
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center',
|
||||
justifyContent: 'center', height: '100vh', padding: '2rem',
|
||||
background: '#0f172a', color: '#e2e8f0', fontFamily: 'system-ui'
|
||||
}}>
|
||||
<h1 style={{ fontSize: '1.5rem', marginBottom: '0.5rem' }}>⚠️ 应用遇到错误</h1>
|
||||
<p style={{ color: '#94a3b8', marginBottom: '1rem', maxWidth: '400px', textAlign: 'center' }}>
|
||||
{this.state.error?.message || '未知错误'}
|
||||
</p>
|
||||
<button
|
||||
onClick={this.handleReset}
|
||||
style={{
|
||||
padding: '0.5rem 1.5rem', borderRadius: '0.5rem',
|
||||
background: '#3b82f6', color: 'white', border: 'none',
|
||||
cursor: 'pointer', fontSize: '0.875rem'
|
||||
}}
|
||||
>
|
||||
重试
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return this.props.children
|
||||
}
|
||||
}
|
||||
|
||||
export default ErrorBoundary
|
||||
Reference in New Issue
Block a user