我有一个提取Epic,如果用户无权访问服务器端资源,则可能返回401或403。如果是这种情况,我想在此Epic期间进行重定向。
现在我正在这样做:
export const fetch$ = <T = any>(req: IRequest) =>
from(performFetch<T>(req)).pipe(
switchMap(res => of(res)),
catchError(e => {
if (e.status === 401 || e.status === 403) {
window.location.replace(`/login?fwd=${encodeURIComponent(window.location.pathname)}`);
return NEVER;
}
return of(e);
})
);
performFetch
只是一个简单的函数,它执行访存并返回一个Promise。
我正在使用window.location.replace
,到目前为止,它仍然可以正常工作,但是有人告诉我它会弄乱React。
我尝试使用connected-react-router
并返回push
操作,但未执行重定向。
我可以继续这样做吗,还是有更好的方法?
不需要使用window.location.replace
,因为您已经安装了react-router
或connected-react-router
,它们可以处理应用程序中的组件导航。
您可以考虑使用replace
或push
。
如果希望返回操作,则必须使用of
运算符将其包装。
of
或者,您可以简单地调用import { replace } from 'connected-react-router'.
export const fetch$ = <T = any>(req: IRequest) =>
from(performFetch<T>(req)).pipe(
switchMap(res => of(res)),
catchError(e => {
if (e.status === 401 || e.status === 403) {
of(replace(`/login?fwd=${encodeURIComponent(window.location.pathname)}`));
}
return of(e);
})
);
/ replace
作为副作用,同时返回其他内容。
push