【发布时间】:2019-07-17 11:22:30
【问题描述】:
抱歉,我知道有人问过这个问题,但我找不到一个适合我的示例。似乎很难理解是否有这么多人在为此苦苦挣扎。
我只需要知道如何在 React 中以一种干净、简单的方式捕获错误。我正在使用 CRA 2.0/React 16.7。我想要一个动作级别的 try/catch 块,因为这是业务逻辑集中在我的应用程序中的地方。
我阅读并按照描述实现了它,但我的 ErrorBoundary 对象从未捕获错误。
例子:
import React, { Component } from "react";
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log("ErrorBoundary: ", error);
console.log("ErrorBoundary: ", info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
我在顶层包装我的路线:
return (
<BrowserRouter>
<ErrorBoundary>
<div className="main-container">
<SideBar />
<div className="some-class">
<Switch>
<Route path="/events" component={Events} />
<Route exact path="/" component={Index} />
</Switch>
</div>
</div>
</ErrorBoundary>
</BrowserRouter>
);
在上面的“事件”中,我进行了一个 API 调用,它在 API 端抛出了 500 错误:
componentDidMount() {
this.props.getAllEvents();
}
这是 Redux 操作:
export const getAllEvents = () => {
return async (dispatch, getState) => {
try {
let state = getState();
const result = await get({
state: state,
route: "/v1/events"
});
dispatch({
type: GET_EVENTS,
payload: result
});
} catch (e) {
console.log("Something went wrong at action...");
}
};
};
..."get()" 只是包装了一个 Axios GET - 没什么特别的。
我在控制台中看到来自失败的 API 调用的 500 错误。从上面的 catch 块中,我从未在控制台中看到“出现问题...”,尽管在调试时该行确实被击中。
“componentDidCatch()”方法永远不会被调用——“hasError”总是假的,它总是渲染子元素。
如果我删除 API 端点中的 throw 块,一切正常,并且我得到了我的数据。我只是无法在 UI 级别捕获错误。我在“componentDidMount()”中尝试了 try/catch,我尝试在操作中删除 try/catch 块...行为没有改变。
提前致谢。
【问题讨论】:
标签: javascript reactjs redux error-handling