Redux Saga - 将相似(但不是全部)的动作分组到 takeLeading / takeLatest
Redux Saga - group similar (but not all) actions into takeLeading / takeLatest
我目前正在一个项目中使用 redux-saga,我想用它来防止多次请求相同的资源。
目前我在同一页面上有多个组件请求资源(即调度{types: "REQUEST_POST_COMMENTS", postId: <postIdHere>}
)
我有这个故事:
export function* loadPostComments() {
yield takeLatest("REQUEST_POST_COMMENTS", loadPostComments);
}
我的页面同时发送以下操作:
{types: "REQUEST_POST_COMMENTS", postId: 123}
{types: "REQUEST_POST_COMMENTS", postId: 321}
{types: "REQUEST_POST_COMMENTS", postId: 123}
我的目标是 loadPostComments
被调用两次,一次是 post 123,一次是 post 321。
我已经在测试版中切换到 takeLeading
- 但是这只会调用 loadPostComments
一次。
有什么方法可以使用模式定义传奇,但 takeLatest
按 action.type
值对它们进行分组?或任何实现类似目标的方法?
我的解决方案
您必须保存遇到的 postId
s 并在:
之后保存给他们
function* watchRequestPostComments() {
const encounteredPostIds = new Set()
while(true) {
const { postId } = yield take('REQUEST_POST_COMMENTS')
if (!encounteredPostIds.has(postId) {
yield fork(loadPostComments, postId)
}
encounteredPostIds.add(postId)
}
}
说明
似乎不存在一种特定的 redux-saga-esque 方式来执行此操作。无论如何,您必须跟踪这些 ID。
我已经回答了关于 的类似问题。
P.S.: 这看起来像是一个无穷无尽的递归。一定是无意的名称冲突:
export function* loadPostComments() {
yield takeLatest("REQUEST_POST_COMMENTS", loadPostComments)
}
我目前正在一个项目中使用 redux-saga,我想用它来防止多次请求相同的资源。
目前我在同一页面上有多个组件请求资源(即调度{types: "REQUEST_POST_COMMENTS", postId: <postIdHere>}
)
我有这个故事:
export function* loadPostComments() {
yield takeLatest("REQUEST_POST_COMMENTS", loadPostComments);
}
我的页面同时发送以下操作:
{types: "REQUEST_POST_COMMENTS", postId: 123}
{types: "REQUEST_POST_COMMENTS", postId: 321}
{types: "REQUEST_POST_COMMENTS", postId: 123}
我的目标是 loadPostComments
被调用两次,一次是 post 123,一次是 post 321。
我已经在测试版中切换到 takeLeading
- 但是这只会调用 loadPostComments
一次。
有什么方法可以使用模式定义传奇,但 takeLatest
按 action.type
值对它们进行分组?或任何实现类似目标的方法?
我的解决方案
您必须保存遇到的 postId
s 并在:
function* watchRequestPostComments() {
const encounteredPostIds = new Set()
while(true) {
const { postId } = yield take('REQUEST_POST_COMMENTS')
if (!encounteredPostIds.has(postId) {
yield fork(loadPostComments, postId)
}
encounteredPostIds.add(postId)
}
}
说明
似乎不存在一种特定的 redux-saga-esque 方式来执行此操作。无论如何,您必须跟踪这些 ID。
我已经回答了关于
P.S.: 这看起来像是一个无穷无尽的递归。一定是无意的名称冲突:
export function* loadPostComments() {
yield takeLatest("REQUEST_POST_COMMENTS", loadPostComments)
}