我从这里了解到:
componentDidCatch:
componentDidCatch
getDerivedStateFromError:
getDerivedStateFromError
不过,我还是有些困惑:
问题中的陈述大部分是正确的。当前,SSR不支持错误边界,getDerivedStateFromError并且componentDidCatch不会影响服务器端。
他们都捕获相同类型的错误吗?还是每个生命周期都会捕获不同的错误?
他们正在捕获相同的错误,但是处于不同的阶段。以前这可能是componentDidCatch单独使用的:
static getDerivedStateFromError() { return { hasError: true }; }
和
componentDidCatch() { this.setState({ hasError: true }); }
做同样的事情,componentDidCatch直到将对异步渲染的支持添加到服务器端之前,它没有机会在服务器端得到支持ReactDOMServer。
ReactDOMServer
我应该总是同时使用两者吗(可能在同一个“捕捉错误”组件中使用)?
您 可以同时 使用。文档中的示例显示:
class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, info) { logComponentStackToMyService(info.componentStack); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
在这种情况下,责任在他们之间分配。getDerivedStateFromError这样做是唯一有益的,即如果发生错误,则更新状态,同时componentDidCatch提供副作用,并且可以this在需要时访问组件实例。
this
“使用componentDidCatch进行错误恢复不是最佳选择,因为它强制后备UI始终同步呈现”这有什么问题?
新的React版本旨在实现更高效的异步渲染。正如评论中提到的那样,对于后备UI来说,同步渲染并不是一个大问题,因为它可以被视为边缘情况。