[英]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 任务。
在上面的代码中,我得到了这个:
但我预计它会是这样的:
我感谢任何帮助,提前致谢。
如果您查看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.