-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.html
73 lines (60 loc) · 2.2 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>错误边界</title>
</head>
<body>
<div id="root"></div>
<script src="../libs/react.min.js"></script>
<script src="../libs/react-dom.min.js"></script>
<script src="../libs/babel.min.js"></script>
<script type="text/jsx">
/**
* 错误边界处理:组件出现异常,会触发 static getDerivedStateFromError 和 componentDidCatch 生命周期
*
* static getDerivedStateFromError 的返回值会合并到组件的 state 中作为最新的 state 值
*/
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
errorMsg: ''
};
}
static getDerivedStateFromError(error) {
// 更新 state 使下一次渲染能够显示降级后的 UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
this.setState({errorMsg: error.message})
console.log('异常信息:', error, ' , ', errorInfo )
}
render() {
const { hasError, errorMsg } = this.state;
if (hasError) {
// 你可以自定义降级后的 UI 并渲染
return <h1>Something went wrong, Error Message: {errorMsg}</h1>;
}
return this.props.children;
}
}
const App = () => {
const [count, setCount] = React.useState(0);
if (count > 0) {
throw TypeError('数据异常');
}
return (
<div>
<h2>App 组件</h2>
<p>count: { count }</p>
<button onClick={() => setCount(count + 1)}>increment</button>
</div>
);
}
ReactDOM.render(<ErrorBoundary><App /></ErrorBoundary>, root);
</script>
</body>
</html>