下面的代码是redux-saga中rootSaga的试用版
有人可以告诉我有什么区别吗?
// kind 1
export default function* rootProjectSaga (): IterableIterator<any> {
yield all([
takeEvery(TRANSFER_PROJECT, transferProject as any),
takeLatest(LOAD_PROJECTS, getProjects as any)
])
}
// kind 2
export default function* rootProjectSaga (): IterableIterator<any> {
yield takeEvery(TRANSFER_PROJECT, transferProject as any)
yield takeLatest(LOAD_PROJECTS, getProjects as any)
}
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(rootProjectSaga)
答案 0 :(得分:2)
export default function* rootProjectSaga (): IterableIterator<any> {
yield takeEvery(TRANSFER_PROJECT, transferProject as any)
yield takeLatest(LOAD_PROJECTS, getProjects as any)
}
此代码将侦听曾经发生的每个TRANSFER_PROJECT,并在发生时调用transferProject。传奇故事的第二行从未到达,因为takeEvery永远不会完成。
export default function* rootProjectSaga (): IterableIterator<any> {
yield all([
takeEvery(TRANSFER_PROJECT, transferProject as any),
takeLatest(LOAD_PROJECTS, getProjects as any)
])
}
此代码将派生两个效果以并行运行。前者将监听每个TRANSFER_PROJECT,后者将监听每个LOAD_PROJECTS。这两个效果彼此无关,并且将按照动作发生的顺序调用transferProject和getProjects。
我的要求是在TRANSFER_PROJECT之后,我将进行LOAD_PROJECTS。
如果您是想等待TRANSFER_PROJECT动作,然后运行transferProject,然后等待LOAD_PROJECTS,然后运行getProjects,可以这样做:
export default function* rootProjectSaga () {
const transferAction = yield take(TRANSFER_PROJECT);
yield call(transferProject, transferAction);
const loadAction = yield take(LOAD_PROJECTS);
yield call(getProjects, loadAction);
}
请注意,以上代码不会注意到在TRANSFER_PROJECT之前发生的任何LOAD_PROJECTS动作,也不会在等待LOAD_PROJECTS期间发生的任何TRANSFER_PROJECT动作。
此外,如果您希望这种情况发生不止一次,则需要将其包装在循环中:
export default function* rootProjectSaga () {
while (true) {
const transferAction = yield take(TRANSFER_PROJECT);
yield call(transferProject, transferAction);
const loadAction = yield take(LOAD_PROJECTS);
yield call(getProjects, loadAction);
}
}