RxJs - Redux-Observable Navigate after Action Fulfilled

RxJs - Redux-Observable Navigate after Action Fulfilled

与其说这是一个实际问题,不如说这是一个代码审查请求。

我下面有这段代码,如果身份验证正确完成,它会重定向用户,我想知道这是否是实现此目的的好|正确|最佳方法。

提前致谢。

  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
          })
        )
      )
    )
  );

takeUntil 运算符在提供的可观察对象完成后立即完成可观察对象。由于 ajax() observable 发出一次,因此 takeUntil.

中没有必要

重定向是 side-effect。建议在 tap 运算符中做副作用。

在适当的史诗中提供重定向 side-effect 通常也是有意义的:

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(),
    );