reactjs尝试捕获渲染不捕获子错误

l2s*_*ver 1 error-handling reactjs

我试图将错误捕获添加到组件的渲染功能。当我在实际的render函数中引发错误时,这种方法很好用,但是如果组件的子代中存在错误,则try不会捕获错误(或者它们被子组件错误处理程序拦截,我不确定?)

无论如何有强迫错误的父母。

const SimpleComponent = React.createClass({
    render: function(){
        try{
            throw 'new error'
            return <div>{this.props.children}</div>
        }catch(e){
            console.log('error', e);        
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

以上作品

const SimpleComponent = React.createClass({
    render: function(){
        try{
            return <div>{this.props.children}</div>
        }catch(e){
            console.log('error', e);        
        }
    }
})

const ChildComponent = React.createClass({
    render: function(){
        throw 'child error'
    }
})

<SimpleComponent>
    <ChildComponent />
</SimpleComponent>
Run Code Online (Sandbox Code Playgroud)

上面没有抓住

Joh*_*ohn 6

使用react 16 中的componentDidCatch () 方法。

检查这个以获取更多信息


Byr*_*ong 5

您可以利用React的BatchingStrategy API轻松包装try/catch所有React代码。这样做的好处window.onerror是,您可以在所有浏览器中获得良好的堆栈跟踪。即使是像Microsoft Edge和Safari这样的现代浏览器也无法提供的堆栈跟踪window.onerror

请注意,此解决方案并不总是可以防止React进入不良状态。但是,此解决方案至少将允许您处理错误,例如显示错误标语/模式,或将堆栈跟踪错误日志发送到服务。

这是React 15.4的样子:

import ReactUpdates from "react-dom/lib/ReactUpdates";
import ReactDefaultBatchingStrategy from "react-dom/lib/ReactDefaultBatchingStrategy";

let isHandlingError = false;
const ReactTryCatchBatchingStrategy = {
  // this is part of the BatchingStrategy API. simply pass along
  // what the default batching strategy would do.
  get isBatchingUpdates () { return ReactDefaultBatchingStrategy.isBatchingUpdates; },

  batchedUpdates (...args) {
    try {
      ReactDefaultBatchingStrategy.batchedUpdates(...args);
    } catch (e) {
      if (isHandlingError) {
        // our error handling code threw an error. just throw now
        throw e;
      }

      isHandlingError = true;
      try {
        // replace this with whatever error handling logic you like.
        // e.g. dispatch redux action notifying the app that an error occurred:
        // `store.dispatch({type: "EXCEPTION", payload: e});`
        console.error(e);
      } finally {
        isHandlingError = false;
      }
    }
  },
};

ReactUpdates.injection.injectBatchingStrategy(ReactTryCatchBatchingStrategy);
Run Code Online (Sandbox Code Playgroud)

完整的文章在这里:https ://engineering.classdojo.com/blog/2016/12/10/catching-react-errors/