我正在使用与redux的反应。在redux层我使用thunk。所以组件调用action,redux action调用一个新层 - >服务。该服务处理http调用。当响应正常时 - 我使用thunk提供的调度并返回到reducer。当响应错误时,我想重定向用户,我找不到办法。我错过了路由器及其替换方法。
答案 0 :(得分:0)
您可以捕获触发动作创建者
的组件内部function doAction() {
return (dispatch) => {
return fetch(...).then(...)
}
}
class Component extends React.Component {
onClickButton = () => {
this.props.doAction().catch(() => {
this.props.router.replace(...)
})
}
}
我假设您connect
已正确编辑并且router
作为道具传递(或context
- 只要它可用于组件)
这样做的一个缺点是,无论何时使用该动作创建者,都必须复制此功能。您可以将路由器作为动作创建者的参数提供,但我不确定这是否违反标准练习/反模式。
另一种选择是使用window.location
答案 1 :(得分:0)
好的,我想我已经知道了。我创建了一个名为ResponseError的通用redux动作。每次HTTP调用返回错误时,我都会在我的所有服务中调度此操作。然后在reducer中我只是打开商店的布尔标志,在主应用程序页面中我会听这个标志。如果它打开 - >做你想做的事。
答案 2 :(得分:0)
如果您正在将axios用于处理http调用的服务,则可以使用其拦截器。这样,您不需要在每个action / reducer-action上都有一个处理程序。
import axios from 'axios';
axios.interceptors.response.use(
res => interceptResponse(res),
err => interceptError(err)
);
const interceptResponse = response => {
// nothing to do here, return back response
return response;
};
const interceptError = error => {
if (error.response.status === 404 || error.response.status === 403) {
// redirect to another react router page
history.push('/error404');
} else if (error.response.status === 401) {
return Promise.reject(error);
}
};
从我在GitHub上的示例项目中引用:https://github.com/mosufy/serverless-react/blob/develop/client/site/src/lib/sdk.js#L90