6.classComponents.md

Class Component

基于ES6的Class组件

  1. 它基于React.components

  2. 我们要使用super来传递上一级给的Props

  3. 使用constructor来初始化this.state,以及事件绑定

  4. 使用生命周期

错误处理

使用componentDidCatch生命周期钩子.这个钩子的作用是捕获子组件(记得啊,是子组件)的错误, 像try-catch函数.

getDerivedStateFromError 如果我们产生了错误, 那么就会触发这个钩子函数.那么在这个钩子函数中, 我们就可以进行处理了。

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
// mostly code from reactjs.org/docs/error-boundaries.html
import React, { Component } from "react";
import { Link, Redirect } from "@reach/router";

class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, redirect: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("ErrorBoundary caught an error", error, info);
}
componentDidUpdate() {
if (this.state.hasError) {
// 5s后自动进行重定向
setTimeout(() => this.setState({ redirect: true }), 5000);
}
}
render() {
if (this.state.redirect) {
return <Redirect to="/" />;
}

if (this.state.hasError) {
// 如果捕捉到错误, 则显示
return (
<h1>
There was an error with this listing. <Link to="/">Click here</Link>{" "}
to back to the home page or wait five seconds
</h1>
);
}
// 如果没有捕捉到错误, 那么你应该把组件往下传递
return this.props.children;
}
}

export default ErrorBoundary;