面试题答案
一键面试用于错误处理的生命周期方法
- componentDidCatch(error, errorInfo)
- 作用范围:用于捕获子组件树中任何位置抛出的错误,包括子组件的渲染、生命周期方法以及构造函数中的错误。但不会捕获自身组件抛出的错误。
- 时机:在子组件树抛出错误后,会在渲染阶段、生命周期方法和构造函数之后被调用。
- static getDerivedStateFromError(error)
- 作用范围:同样捕获子组件树中抛出的错误,不捕获自身组件错误。
- 时机:在组件捕获到错误后,渲染阶段调用,可用于更新 state 以反映错误状态。
代码示例
import React, { Component } from'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
componentDidCatch(error, errorInfo) {
// 记录错误信息,可用于日志上报等
console.log('Error caught in componentDidCatch:', error, errorInfo);
this.setState({ hasError: true });
}
static getDerivedStateFromError(error) {
// 这里可以返回新的 state 以告知 UI 发生了错误
console.log('Error caught in getDerivedStateFromError:', error);
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <div>There was an error in a child component.</div>;
}
return this.props.children;
}
}
class ChildComponent extends Component {
constructor(props) {
super(props);
// 模拟构造函数抛出错误
throw new Error('Constructor error in ChildComponent');
}
render() {
return <div>Child component content</div>;
}
}
class App extends Component {
render() {
return (
<ErrorBoundary>
<ChildComponent />
</ErrorBoundary>
);
}
}
export default App;
在上述代码中,ErrorBoundary
组件通过 componentDidCatch
和 static getDerivedStateFromError
方法捕获 ChildComponent
构造函数中抛出的错误,并在 ErrorBoundary
的 render
方法中根据错误状态展示不同的 UI。