react如何接收异常
React 中接收异常的方法
在 React 中,异常处理可以通过多种方式实现,包括全局错误边界、组件级错误边界以及异步代码的异常捕获。
使用 Error Boundaries 捕获组件异常
Error Boundaries 是 React 提供的用于捕获子组件树中 JavaScript 错误的组件。通过定义一个类组件并实现 componentDidCatch 或 static getDerivedStateFromError 方法,可以捕获子组件中的异常。
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught by ErrorBoundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <div>Something went wrong.</div>;
}
return this.props.children;
}
}
使用时将需要捕获异常的组件包裹在 ErrorBoundary 中:
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
捕获异步代码中的异常
Error Boundaries 无法捕获异步代码(如 setTimeout、fetch 等)中的异常,需要手动使用 try/catch 处理。
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
} catch (error) {
console.error('Fetch error:', error);
}
};
fetchData();
}, []);
全局错误处理
可以通过 window.onerror 或 window.addEventListener('error', ...) 捕获全局未处理的异常。
window.addEventListener('error', (event) => {
console.error('Global error:', event.error);
});
处理事件处理器中的异常
在事件处理器中直接使用 try/catch 捕获异常。
const handleClick = () => {
try {
// 可能抛出异常的代码
} catch (error) {
console.error('Event handler error:', error);
}
};
总结
- 对于组件渲染中的异常,使用 Error Boundaries。
- 对于异步代码,使用
try/catch。 - 对于全局异常,使用
window.onerror或事件监听器。 - 事件处理器中的异常直接使用
try/catch处理。







