每天30s系列|什么是 React 中的错误边界?
回答
错误边界是 React 捕获子组件树中所有 JavaScript 错误的组件,他可以记录这些错误,并将错误显示在 UI 上来替代组件树的崩溃。
componentDidCatch 的新生命周期方法,那么他将成为错误边界。
class ErrorBoundary extends React.Component { constructor(props) {super(props)this.state = { hasError: false }}componentDidCatch(error, info) {// Display fallback UIthis.setState({ hasError: true })// You can also log the error to an error reporting servicelogErrorToMyService(error, info)}render() {if (this.state.hasError) {// You can render any custom fallback UIreturn <h1>Something went wrong.</h1>}return this.props.children}}
加分回答
-
componentDidCatch:用于错误边界,他是实现此方法的组件。他允许组件去捕获其子组件树中任意位置的 JavaScript 错误,打印错误,并使用 UI 展现错误信息。但他可能在未来的版本中被废弃,改用static getDerivedStatFromError()来代替。 当任何一个子组件在渲染过程中、在一个生命周期的方法中或在构造函数中发生错误时
static getDerivedStateFromError(),componentDidCatch()将会被调用。
