我正在尝试为一个简单的应用程序添加错误边界。当我单击按钮时,应该在屏幕上显示“出了点问题”。但是在我的情况下,它不是那样显示的。尝试在控制台上记录它。当我在屏幕上运行此应用程序时,它显示错误:单击不正确
App.js
import './App.css';
import Button from './Components/Button';
import ErrorBoundary from './Components/ErrorBoundary';
function App() {
return (
<div className="App">
<ErrorBoundary>
<Button />
</ErrorBoundary>
</div>
);
}
export default App;
Button.js import React, { Component } from 'react';
class Button extends Component {
constructor(props) {
super(props);
this.state = { error: null };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log("Test Button")
this.state = { error: true};
throw new Error('Not a correct click');
}
render() {
if (this.state.error) {
return <h1>Caught an error!</h1>
}
return <button onClick={this.handleClick} style={{ color: 'white', background: 'blue', width: 200, height: 50 }}>Throw Error</button>
}
}
export default Button;
ErrorBoundary.js import React, { Component } from 'react'
class ErrorBoundary extends Component {
constructor (props){
super(props);
this.state = {
hasError: false,
error: null,
info: null
}
}
static getDerivedStateFromError(error){
this.state.hasError = true
}
componentDidCatch (error,info){
console.log(error);
console.log(info)
}
render() {
if(this.state.hasError){
return <h2>Something went wrong</h2>
}
return this.props.children;
}
}
export default ErrorBoundary;
最佳答案
一切看起来都是正确的,但是根据docs:
错误边界不会捕获以下方面的错误:
以我的经验,错误边界会捕获render()中的错误并阻止其在边界外传播。
错误边界背后的目的是避免半破坏的React渲染状态。
建议使用
try/catch
捕获事件处理程序中的错误。将
throw
移至Button.render
应该有助于ErrorBoundary捕获示例中的错误:handleClick() {
console.log("Test Button")
this.state = { error: true};
// throw new Error('Not a correct click');
}
render() {
if (this.state.error) {
throw new Error('Not a correct click')
return <h1>Caught an error!</h1>
}
return <button onClick={this.handleClick} style={{ color: 'white', background: 'blue', width: 200, height: 50 }}>Throw Error</button>
}
关于javascript - 如何在响应中使用错误边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64758959/