簡體   English   中英

有沒有辦法在 RxJS / Redux-observable 中連接非 Redux 操作?

[英]Is there a way to concat non-Redux actions in RxJS / Redux-observable?

成功登錄后,我嘗試在獲取用戶配置之前將令牌存儲在本地存儲中。 目前,我只是在獲取 return 語句中的配置之前從mergeMap存儲令牌。 但是,我很確定有一種方法可以使用concatconcatMap調用 store 和 fetch 函數。

const authEpic = action$ =>
  action$.pipe(
    ofType('auth/AUTHENTICATION_SUCCESS'),
    mergeMap(action => {
      const { jwt } = action.payload;

      localStorage.setItem('token', jwt);

      return of({
        type: 'user/FETCH_CONFIG'
      });
    })
  );

下面是我的嘗試之一,但被證明是不成功的。 盡管在這種情況下可能有其他方法可以從組件內部處理存儲和獲取,但我想知道這種模式應該如何適用於我擁有的其他情況。

const authEpic = action$ =>
  action$.pipe(
    ofType('auth/AUTHENTICATION_SUCCESS'),
    mergeMap(action => {
      const { jwt } = action.payload;

      return concat(
        localStorage.setItem('token', jwt),
        of({ type: 'user/FETCH_CONFIG'})
      );
    })
  );

我會采用您在問題中陳述的第一種方法,因為localStorage.setItem()是同步的,因此在返回FETCH_CONFIG操作之前,它總是會被調用。

但是,如果您正在尋找替代方法,我建議您在返回FETCH_CONFIG操作之前使用tap()運算符分離邏輯。 這也將確保按順序調用這兩個操作。

const authEpic = action$ =>
  action$.pipe(
    ofType('auth/AUTHENTICATION_SUCCESS'),
    tap(({ payload: { jwt } }) => {
      localStorage.setItem('token', jwt);
    }),
    mergeMap((action) => (of({
      type: 'user/FETCH_CONFIG'
    }))
  );

但是,如果您真的想使用concat() ,則需要將localStorage.setItem()操作包裝在of()以將其轉換為可觀察對象,因為concat()要求所有成員都是可觀察對象,並且需要在第二個訂閱( FETCH_CONFIG )可以開始之前等待第一個訂閱( localStorage.setItem() )完成。

const authEpic = action$ =>
  action$.pipe(
    ofType('auth/AUTHENTICATION_SUCCESS'),
    mergeMap(action => {
      const { jwt } = action.payload;

      return concat(
        of(localStorage.setItem('token', jwt)),
        of({ type: 'user/FETCH_CONFIG'})
      );
    }),
  );

也許您可以嘗試使用last()運算符,Concat 會在序列中的每個項目自行完成時發出,這就是它不起作用的原因。

  reuturn concat(
    of(localStorage.setItem('token', jwt)),
    of({ type: 'user/FETCH_CONFIG'})
  ).pipe(last());

concat用於按照先前完成的順序執行可觀察對象。

learnrx.io檢查文檔

你可以把 c​​oncat 想象成 ATM 上的一條線,下一個交易(訂閱)在前一個完成之前不能開始!

在您的示例中,我認為您不需要任何這些運算符,因為您沒有在流程中執行任何異步操作。

您可以簡單地使用以下內容更改您的代碼:

action$.pipe(
  ofType('auth/AUTHENTICATION_SUCCESS'),
  tap(action => localStorage.setItem('token', action.payload)),
  mapTo({ type: 'user/FETCH_CONFIG'})
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM