使用Redux-observables和RxJS在获取史诗期间重定向

问题描述 投票:0回答:1

我有一个提取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操作,但未执行重定向。

我可以继续这样做吗,还是有更好的方法?

reactjs rxjs react-router redux-observable connected-react-router
1个回答
0
投票

不需要使用window.location.replace,因为您已经安装了react-routerconnected-react-router,它们可以处理应用程序中的组件导航。

您可以考虑使用replacepush

如果希望返回操作,则必须使用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
© www.soinside.com 2019 - 2024. All rights reserved.