我想编写一个不允许任何错误破坏整个应用程序的React.js 守卫。在阅读官方文档时,我在codepen中看到了这个例子的链接:https ://codepen.io/gaearon/pen/wqvxGa?editors=0010
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error, errorInfo) {
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}
render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}
class BuggyCounter extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(({counter}) => ({
counter: counter + 1
}));
}
render() {
if (this.state.counter === 5) {
// Simulate a JS error
throw new Error('I crashed!');
}
return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
}
}
function App() {
return (
<div>
<p>
<b>
This is an example of error boundaries in React 16.
<br /><br />
Click on the numbers to increase the counters.
<br />
The counter is programmed to throw when it reaches 5. This simulates a JavaScript error in a component.
</b>
</p>
<hr />
<ErrorBoundary>
<p>These two counters are inside the same error boundary. If one crashes, the error boundary will replace both of them.</p>
<BuggyCounter />
<BuggyCounter />
</ErrorBoundary>
<hr />
<p>These two counters are each inside of their own error boundary. So if one crashes, the other is not affected.</p>
<ErrorBoundary><BuggyCounter /></ErrorBoundary>
<ErrorBoundary><BuggyCounter /></ErrorBoundary>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
这段代码在 codepen 中工作,我知道render 中存在错误,它应该存在,在 throw 被“调用”的那一刻,错误被成功捕获并且不会丢弃整个应用程序(如预期的那样)。 但是当我复制这段代码时,它不像在沙箱中那样工作,即在熔断器需要捕获错误的那一刻,它并没有美化,而是“放置”整个应用程序, 问题:熔断器为什么工作正如它应该在代码笔中一样,但是当我把它放在我的文件中时,一切都会中断。我的电脑可能是什么问题
这是我控制台中的错误
照片 这是屏幕上的错误照片:

我PC上的react版本是16.12.0,react-dom的版本是一样的。
PS:代码 1 合 1 就像在沙盒中一样
没问题,就是开发模式开的简单报错,直接关闭就可以了..