情境:post data 到不同的 key,但使用相同的 API 和 action
import { cancel, delay, fork, take } from 'redux-saga/effects'; export default function* debouncePerKey({ pattern, selector, timeout, preFn, callApi, }) { const map = new Map(); while (true) { const action = yield take(pattern); const key = selector(action); const existingTask = map.get(key); if (preFn) { yield preFn(action); } if (existingTask) { yield cancel(existingTask); } const newTask = yield fork(function* () { yield delay(timeout); map.delete(key); yield callApi(action); }); map.set(key, newTask); } }
加入 root saga
fork(() => debouncePerKey({ pattern: postExamAnswerRequest.type, selector: (action) => action.payload.payload.question_id, timeout: 500, preFn: updateAnswer, callApi: handlePostExamAnswerRequest, }), )