Reactjs 循环混乱中的重演传奇
我有以下(第一个)传奇故事: 所以,它不能正常工作。如果我把Reactjs 循环混乱中的重演传奇,reactjs,redux,redux-saga,Reactjs,Redux,Redux Saga,我有以下(第一个)传奇故事: 所以,它不能正常工作。如果我把console.log放在里面,它只会被记录一次,并且只会出现第一个结果。所以它不能像我希望的那样工作(我希望它能像我在第一部传奇中发布它一样工作很多次) 但是,如果我改用takeEvery: export function* anotherStuffWatcher() { yield takeEvery(someActionType, anotherStuff); } 它工作正常-正在处理所有请求 我的最后一个问题-为什么我使
console.log
放在里面,它只会被记录一次,并且只会出现第一个结果。所以它不能像我希望的那样工作(我希望它能像我在第一部传奇中发布它一样工作很多次)
但是,如果我改用takeEvery
:
export function* anotherStuffWatcher() {
yield takeEvery(someActionType, anotherStuff);
}
它工作正常-正在处理所有请求
我的最后一个问题-为什么我使用while(true)
it只处理第一个请求而不是每个请求?为什么我使用takeEvery时它能正常工作?谢谢大家!
它只被记录一次
这是因为call
是阻塞效应。假设apiCall
需要一些时间。因此,当这一呼吁发生时,你的传奇故事被阻止,没有采取新的行动
export function* anotherStuff() {
while (true) {
const action = yield take(someAction);
const { actionId } = action;
try {
const { data } = yield call(apiCall, elem); // this is blocking call
yield put(someSuccessAction(Action, data));
}
}
}
为了避免这种情况,您可以使用takeEvery
helper来处理与模式匹配的“执行每一个”操作。或者你可以用它来缓冲未来的行动
export function* anotherStuff() {
// buffers up to 10 actions
// or you could provide another buffering strategy via
// second argument https://redux-saga.js.org/docs/api/#buffers
const someChannel = yield actionChannel(someAction);
while (true) {
const action = yield take(someChannel);
const { actionId } = action;
try {
const { data } = yield call(apiCall, elem); // this is blocking call
yield put(someSuccessAction(Action, data));
} catch(blackhole) {}
}
}
我在使用这个
actionChannel
的方式和你写它的方式一样,也和它在官方文件中发布的方式一样。我收到以下错误:错误:获取(模式或通道):参数[object object]不是有效通道或有效模式
。这很奇怪,因为我使用的动作与我在take
中使用的动作相同……好吧,你忘记了yield
之前的actionChannel(someAction)
;
export function* anotherStuff() {
while (true) {
const action = yield take(someAction);
const { actionId } = action;
try {
const { data } = yield call(apiCall, elem); // this is blocking call
yield put(someSuccessAction(Action, data));
}
}
}
export function* anotherStuff() {
// buffers up to 10 actions
// or you could provide another buffering strategy via
// second argument https://redux-saga.js.org/docs/api/#buffers
const someChannel = yield actionChannel(someAction);
while (true) {
const action = yield take(someChannel);
const { actionId } = action;
try {
const { data } = yield call(apiCall, elem); // this is blocking call
yield put(someSuccessAction(Action, data));
} catch(blackhole) {}
}
}