|
| 1 | +import { render } from "@reactunity/renderer"; |
| 2 | +import React, { useState } from "react"; |
| 3 | + |
| 4 | +function ErrorChild2() { |
| 5 | + const [state, setState] = useState(null); |
| 6 | + |
| 7 | + return <div class="error-child-2"> |
| 8 | + {state.value} |
| 9 | + </div>; |
| 10 | +} |
| 11 | + |
| 12 | +function ErrorChild1() { |
| 13 | + return <div class="error-child-1"> |
| 14 | + <ErrorChild2 /> |
| 15 | + </div>; |
| 16 | +} |
| 17 | + |
| 18 | +export default function ErrorTest() { |
| 19 | + |
| 20 | + return ( |
| 21 | + <ErrorChild1 /> |
| 22 | + ); |
| 23 | +} |
| 24 | + |
| 25 | + |
| 26 | +const createdRefs = new Set(); |
| 27 | + |
| 28 | +function createRef(ref) { |
| 29 | + if (ref && !createdRefs.has(ref)) { |
| 30 | + createdRefs.add(ref); |
| 31 | + console.log("Created ref", ref); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +export class ErrorBoundary extends React.Component<any, any> { |
| 36 | + constructor(props) { |
| 37 | + super(props); |
| 38 | + this.state = { hasError: false, error: null }; |
| 39 | + } |
| 40 | + |
| 41 | + static getDerivedStateFromError(error) { |
| 42 | + // Update state so the next render will show the fallback UI. |
| 43 | + return { hasError: true, error }; |
| 44 | + } |
| 45 | + |
| 46 | + render() { |
| 47 | + if (this.state.hasError) { |
| 48 | + return <view ref={createRef} |
| 49 | + id='__react-unity-error-boundary' |
| 50 | + style={{ color: 'crimson', padding: 20, fontSize: 16 }}> |
| 51 | + <view style={{ marginBottom: '12px' }}> |
| 52 | + {this.state.error?.message || ''} |
| 53 | + </view> |
| 54 | + <view>{this.state.error?.stack || ''}</view> |
| 55 | + </view>; |
| 56 | + } |
| 57 | + |
| 58 | + return this.props.children; |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +render( |
| 63 | + <ErrorBoundary> |
| 64 | + <ErrorTest /> |
| 65 | + </ErrorBoundary>, { disableHelpers: true }); |
0 commit comments