RxJs-完成动作后Redux可观察的导航

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

这是一个代码审查请求,而不是实际的问题。

我下面有这段代码,如果身份验证正确完成,我将重定向用户,并且我想知道这是否是实现此目标的一种好方法。

提前感谢。

  const loginEpic = action$ =>
  action$.pipe(
    ofType(LOGIN_USER),
    mergeMap(action =>
      ajax({
        url: `${BASE_URL}/auth/login`,
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: action.payload
      }).pipe(
        map(response => loginUserFulfilled(response)),
        takeUntil(
          action$.pipe(
            ofType(LOGIN_USER_FULFILLED),
            mapTo(history.push("/stuff"))
          )
        ),
        catchError(error =>
          of({
            type: LOGIN_USER_REJECTED,
            payload: error.xhr.response,
            error: true
          })
        )
      )
    )
  );
rxjs navigation redux-observable
1个回答
0
投票

takeUntil运算符在提供的可观察值完成后立即完成一个可观察值。由于ajax()可观察到的发射一次,因此takeUntil中不需要。

重定向是一个副作用。建议在tap运算符中进行副作用。

在适当的史诗中提供重定向副作用通常也很有意义:

import { tap, ignoreElements } from "rxjs/operators";

const loginEpic = action$ =>
    action$.pipe(
        ofType(LOGIN_USER),
        mergeMap(action =>
            ajax({
                url: `${BASE_URL}/auth/login`,
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: action.payload
            }).pipe(
                map(response => loginUserFulfilled(response)),
                catchError(error =>
                    of({
                        type: LOGIN_USER_REJECTED,
                        payload: error.xhr.response,
                        error: true
                    })
                )
            )
        )
    );

const loginRedirectEpic = action$ =>
    action$.pipe(
        ofType(LOGIN_USER_FULFILLED),
        tap(() => history.push("/stuff")),
        ignoreElements(),
    );
© www.soinside.com 2019 - 2024. All rights reserved.