Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Q010】了解 React 中的 ErrorBoundary 吗,它有那些使用场景 #11

Open
shfshanyue opened this issue Nov 5, 2019 · 9 comments
Labels

Comments

@shfshanyue
Copy link
Owner

No description provided.

@shfshanyue
Copy link
Owner Author

待答

@geekftz
Copy link

geekftz commented Dec 9, 2019

从其他文章里看到的 避免错误渲染白屏做异常中间处理的嵌套组件
class ErrorBoundary extends Component {
static getDerivedStateFromError() {
return { hasError: true };
}
state = {
hasError: false,
};
componentDidCatch(error, info) {
// reportError(error, info);
}
render() {
const { hasError } = this.state;
const { children } = this.props;
if (hasError) {
return

系统异常,请稍后再试
;
}
return children;
}
}
function render(Component, props) {
const rootElement = document.getElementById("root");
ReactDOM.render(

<Component {...props} />
,
rootElement
);
}

作者:蚂蚁保险体验技术
链接:https://juejin.im/post/5de91d0f51882512400acafd
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

@BertieGo
Copy link

是 react 内的一个钩子,用于在组件内发生了 js 错误时候的错误处理。
使用场景是在发生 js 报错的时候不至于说白屏,可以转去别的页面提示用户这里报了错,转用别的去到去继续操作。

@baihech
Copy link

baihech commented Dec 26, 2019

这不就是try catch么。。。

@baihech
Copy link

baihech commented Dec 26, 2019

错误不抛出,交给catch处理,然鹅并不能预先知道错误类型。。。

@libin1991
Copy link

前端防御性编程

@into-piece
Copy link

了解,在推出之前报错会直接白屏,总是需要我们前端进行手动try catch,react16新增了两个生命周期componentdidcatch和static getDerivedStateFromError从框架级别让我们更方便捕捉异常并显示备用ui。其实就是在整个workloop外面包一层try catch,报错时候遍历父组件找到这两个生命周期并把堆栈信息塞给生命周期进行判断。

@into-piece
Copy link

顺带一句suspense的原理好像也是这个

@Murraya-paniculata
Copy link

嵌套的比较深的组件存在出错的风险,组件自身没有容错机制,会逐层交给外层组件处理。这个过程会导致整个组件树销毁。页面结果就是白屏。而且生产环境不会报出有效的错误信息,不好定位问题。
使用ErrorBoundary 就是在可能出错的组件上套一层组件,在这个新的组件中去容错

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

7 participants