【问题标题】:Redux-saga takeLatest conditionallyRedux-saga 有条件地获取最新
【发布时间】:2020-09-10 04:30:06
【问题描述】:

我有一个与 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:说唱(因 [3] 而取消)
  3. fetchSongs - songType: Pop(因 [4] 而取消)
  4. fetchSongs - songType:说唱(因 [5] 而取消)
  5. fetchSongs - 歌曲类型:流行音乐

但我预计会是这样的:

  1. fetchSongs - 歌曲类型:嘻哈
  2. fetchSongs - songType:说唱(因 [4] 而取消)
  3. fetchSongs - songType: Pop(因 [5] 而取消)
  4. fetchSongs - 歌曲类型:说唱
  5. fetchSongs - 歌曲类型:流行音乐

感谢任何帮助,在此先感谢。

【问题讨论】:

  • 您如何期望redux 知道4 会发生?如果24 之间的持续时间很长,那么redux 怎么知道要等待多长时间?最好在React层处理这样的逻辑
  • 嗨@codemax,感谢您的回复,我不提及持续时间,因为takeLatest的逻辑是如果调用4时2仍在运行,则2将被取消。但我希望它只应在下一次 saga 运行具有与正在运行的任务相同的 songType 时取消。

标签: javascript reactjs react-redux redux-saga


【解决方案1】:

如果您查看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);
}

【讨论】:

  • 您好克里斯蒂安,感谢您的回复。我会将其标记为已接受的anwser
猜你喜欢
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多