Tsa*_*mba 7 javascript error-handling reactjs redux
抱歉,我知道有人问过这个问题,但我找不到适合我的例子。如果有这么多人为此苦苦挣扎,似乎不太容易理解。
我只需要知道如何以干净、简单的方式捕获 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;
Run Code Online (Sandbox Code Playgroud)
我正在顶层包裹我的路线:
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>
);
Run Code Online (Sandbox Code Playgroud)
在上面的“事件”中,我进行了一个 API 调用,该调用在 API 端引发了 500 错误:
componentDidMount() {
this.props.getAllEvents();
}
Run Code Online (Sandbox Code Playgroud)
这是 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...");
}
};
};
Run Code Online (Sandbox Code Playgroud)
...“get()”只是包装一个 Axios GET - 没什么花哨的。
我在控制台中看到 API 调用失败导致的 500 错误。我从未在控制台中从上面的 catch 块中看到“出现问题...”,尽管该行在调试时确实被击中。
“componentDidCatch()”方法永远不会被调用 - “hasError”始终为 false 并且它始终呈现子级。
如果我删除 API 端点中的 throw 块,一切都会正常工作并且我会获取数据。我只是无法捕获用户界面级别的错误。我已经在“componentDidMount()”中尝试了 try/catch,我已经尝试删除操作中的 try/catch 块...行为没有改变。
提前致谢。
正如另一个答案正确指出的那样,React 错误边界只会捕获渲染错误。
由于您使用的是 redux,因此您可以针对像您这样的情况构建自己的机制:
error属性的操作。error属性的操作。它接收操作并更新状态树中的“全局错误”状态connected 包装器组件会看到这种状态变化并显示后备 UI。例如:
调度具有属性的操作error:
export const getAllEvents = () => {
return async (dispatch, getState) => {
try {
...
} catch (e) {
dispatch({
type: ERROR,
error: e // dispatch an action that has `error` property
});
}
};
};
Run Code Online (Sandbox Code Playgroud)
减速器看到它并更新该state.error部分:
export default function errorReducer(state = null, action) {
const { type, error } = action;
if (type === RESET_ERROR_MESSAGE) { // an action to clear the error
return null;
} else if (error) { // any type of action, but contains an `error`
return error;
}
return state;
}
Run Code Online (Sandbox Code Playgroud)
现在您将应用程序包装在connected边界中:
function Wrapper({error}) {
if(error) return <h1>Something went wrong</h1>;
return <App/>;
}
export default connect(
state => ({
error: state.error,
})
)(Wrapper);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6272 次 |
| 最近记录: |