本文介绍了Redux-saga 有条件地获取最新信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 redux-saga 的问题,有什么方法可以实现 takeLatest 但有条件.

I have a question related to redux-saga that is there any way to achieve takeLatest but with condition.

例如,我有一个动态的歌曲类型列表(Rap、Pop、Hip_hop...),我想按歌曲类型获取歌曲.我定义了一个类型为FETCH_SONGS_BY_TYPE"的 redux-action;然后将 songType 传递给它.动作看起来像

For example, I have a dynamical list of song types (Rap, Pop, Hip_hop...), I want to fetch the songs by song type. I define an redux-action with type "FETCH_SONGS_BY_TYPE" then pass songType to it. The action will look like

// 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 任务.

So I want that the previous saga task is only canceled if the next saga run has the same songType.

在上面的代码中,我得到了这个:

In above code, I got this:

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


但我预计会是这样:


But I expected it will be like this:

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

感谢您的帮助,提前致谢.

I appreciate any helps, thanks in advance.

推荐答案

如果你看一下 takeLatest,您将看到如何使用低级效果构建此效果.通过此示例,您可以轻松创建自定义效果,该效果仅取消相同音乐流派的操作.

If you take a look at the documentation of takeLatest, you will see how this effect is built using the low-level effects. With this example, you can easily create your custom effect which only cancels actions from the same music genre.

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

这篇关于Redux-saga 有条件地获取最新信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-04 16:23