簡體   English   中英

Redux-saga 有條件地獲取最新信息

[英]Redux-saga takeLatest conditionally

我有一個與 redux-saga 相關的問題,有什么方法可以實現 takeLatest 但有條件。

例如,我有一個動態的歌曲類型列表(Rap、Pop、Hip_hop...),我想按歌曲類型獲取歌曲。 我定義了一個類型為“FETCH_SONGS_BY_TYPE”的 redux-action,然后將 songType 傳遞給它。 動作看起來像

// actions
const fetchSongsByType = songType => ({
  type: FETCH_SONGS_BY_TYPE,
  songType
});
--------------------------------------------------
//saga
function* fetchSongsByTypeSaga(action) {
   // request songs list by action.songType
}
function* Saga() {
  yield takeLatest(FETCH_SONGS_BY_TYPE, fetchSongsByTypeSaga);
}

所以我希望只有在下一個 saga 運行具有相同的 SongType 時才取消上一個 saga 任務。

在上面的代碼中,我得到了這個:

  1. fetchSongs - songType: Hip_hop(因 [2] 取消)
  2. fetchSongs - songType: Rap(因 [3] 取消)
  3. fetchSongs - songType: Pop(因 [4] 取消)
  4. fetchSongs - songType: Rap(因 [5] 而取消)
  5. fetchSongs - 歌曲類型:流行

但我預計它會是這樣的:

  1. fetchSongs - 歌曲類型:Hip_hop
  2. fetchSongs - songType: Rap(因 [4] 取消)
  3. fetchSongs - songType: Pop(因 [5] 而取消)
  4. fetchSongs - 歌曲類型:說唱
  5. fetchSongs - 歌曲類型:流行

我感謝任何幫助,提前致謝。

如果您查看takeLatest的文檔,您將看到如何使用低級效果構建此效果。 通過此示例,您可以輕松創建自定義效果,該效果僅取消相同音樂流派的操作。

takeLatestByType:

const takeLatestByType = (patternOrChannel, saga, ...args) => fork(function*() {
  // hold a reference to each forked saga identified by the type property
  let lastTasks = {};

  while (true) {
    const action = yield take(patternOrChannel);

    // if there is a forked saga running with the same type, cancel it.
    if (lastTasks[action.type]) {
      yield cancel(lastTasks[action.type]);
    }

    lastTasks[action.type] = yield fork(saga, ...args.concat(action));
  }
});

用法:

function* Saga() {
  yield takeLatestByType(FETCH_SONGS_BY_TYPE, fetchSongsByTypeSaga);
}

暫無
暫無

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

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