我尝试在节点6.2.1上运行下一个代码。它会记录 1,2,,然后卡住。我无法理解为什么它不继续执行到线路收益(' TEST')...似乎anotherSaga完成并记录2但控制权没有返回到rootSaga。有人可以帮帮我吗?
const {runSaga, delay} = require('redux-saga');
const {take, put, call} = require('redux-saga/effects');
function* anotherSaga() {
yield call(delay, 1000);
console.log(2);
}
function* rootSaga() {
while(true) {
console.log(1);
yield call(anotherSaga);
console.log(3);
const action = yield take('TEST');
console.log(4);
yield put(action);
}
}
runSaga(
rootSaga(),
{
subscribe(callback) {
return setInterval(() => (callback({type: 'TEST'})), 1000);
},
dispatch(action) {
console.log(action);
},
getState() {}
}
);
更新:但没有runSaga的代码按预期方式运行1,2,3,4
const {createStore, applyMiddleware} = require('redux');
const createSagaMiddleware = require('redux-saga').default;
const {delay} = require('redux-saga');
const {take, put, call} = require('redux-saga/effects');
function* anotherSaga() {
yield call(delay, 2000);
console.log(2);
}
function* rootSaga() {
while(true) {
console.log(1);
yield call(anotherSaga);
console.log(3);
const action = yield take('TEST');
console.log(4);
yield put(action);
console.log('---')
}
}
const rootReducer = (state, action) => {
if (state === undefined) {
return {};
}
return state;
}
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, {}, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
setInterval(() => (store.dispatch({type: 'TEST'})), 1000);
答案 0 :(得分:0)
看起来这是由于subscribe
函数没有返回正确的值。在它之上返回setInterval
的结果,这将是间隔的ID。相反,它应该返回一个函数,redux-saga可以根据docs取消订阅事件。所以你的subscribe
函数看起来应该更像这样:
subscribe(callback) {
const intervalId = setInterval(() => (callback({type: 'TEST'})), 1000);
return () => { clearInterval(intervalId); };
},
用它运行它,我能够看到它循环打印
1
2
3
4
{ type: 'TEST' }
这是多么奇怪,这会导致你的传奇被卡住,但我假设没有从unsubscribe
收到subscribe
函数导致在redux内部搞砸了-saga。