直接参考官方文档:https://zh-hans.reactjs.org/docs/error-boundaries.html 部分 UI 的 JavaScript 错误不应该导致整个应用崩溃,为了解决这个问题,React 16 引入了一个新的概念 —— 错误边界。

    如果一个 class 组件中定义了 [static getDerivedStateFromError()](https://zh-hans.reactjs.org/docs/react-component.html#static-getderivedstatefromerror)[componentDidCatch()](https://zh-hans.reactjs.org/docs/react-component.html#componentdidcatch) 这两个生命周期方法中的任意一个(或两个)时,那么它就变成一个错误边界。当抛出错误后,请使用 static getDerivedStateFromError() 渲染备用 UI ,使用 componentDidCatch() 打印错误信息。

    1. class ErrorBoundary extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.state = { hasError: false };
    5. }
    6. static getDerivedStateFromError(error) {
    7. // 更新 state 使下一次渲染能够显示降级后的 UI
    8. return { hasError: true };
    9. }
    10. componentDidCatch(error, errorInfo) {
    11. // 你同样可以将错误日志上报给服务器
    12. logErrorToMyService(error, errorInfo);
    13. }
    14. render() {
    15. if (this.state.hasError) {
    16. // 你可以自定义降级后的 UI 并渲染
    17. return <h1>Something went wrong.</h1>;
    18. }
    19. return this.props.children;
    20. }
    21. }

    主要是记不能被捕获到错误的情况:

    1. 事件处理
    2. 异步代码(例如 setTimeoutrequestAnimationFrame 回调函数)
    3. 服务端渲染
    4. 它自身抛出来的错误(并非它的子组件)

    踩了第4个的坑…