栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

getDerivedStateFromError和componentDidCatch有什么区别

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

getDerivedStateFromError和componentDidCatch有什么区别

问题中的陈述大部分是正确的。当前,SSR不支持错误边界,

getDerivedStateFromError
并且
componentDidCatch
不会影响服务器端。

他们都捕获相同类型的错误吗?还是每个生命周期都会捕获不同的错误?

他们正在捕获相同的错误,但是处于不同的阶段。以前这可能是

componentDidCatch
单独使用的:

  static getDerivedStateFromError() {    return { hasError: true };  }

  componentDidCatch() {    this.setState({ hasError: true });  }

做同样的事情,

componentDidCatch
直到将对异步渲染的支持添加到服务器端之前,它没有机会在服务器端得到支持
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
在需要时访问组件实例。

“使用componentDidCatch进行错误恢复不是最佳选择,因为它强制后备UI始终同步呈现”这有什么问题?

新的React版本旨在实现更高效的异步渲染。正如评论中提到的那样,对于后备UI来说,同步渲染并不是一个大问题,因为它可以被视为边缘情况。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569052.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号