作为redux-saga的新手,我正在尝试设置一个对行动LANGUAGE_START_CYCLE
作出反应的传奇,并每隔3秒循环一次动作LANGUAGE_CYCLE
。
但是,当我将LANGUAGE_CYCLE
发送到Redux商店时,传奇LANGUAGE_START_CYCLE
永远不会像我期望的那样运行。
知道我做错了什么吗?我怀疑这是一个简单的错误,因为我的其他传奇运行得很好。
// constants/ActionTypes.js
export const LANGUAGE_SET_ACTIVE = "LANGUAGE_SET_ACTIVE";
export const LANGUAGE_START_CYCLE = "LANGUAGE_START_CYCLE";
export const LANGUAGE_STOP_CYCLE = "LANGUAGE_STOP_CYCLE";
export const LANGUAGE_CYCLE = "LANGUAGE_CYCLE";
// actions/language.js
export const cycleLanguage = () => {
return {
type: ActionTypes.LANGUAGE_CYCLE
}
};
// languageSaga.js
import { actionChannel, call, take, put, race } from 'redux-saga/effects'
import * as ActionTypes from '../constants/ActionTypes';
import * as actions from '../actions/language';
const wait = ms => {
new Promise(resolve => {
setTimeout(() => resolve(), ms)
})
};
export default function * languageSaga() {
const channel = yield actionChannel(ActionTypes.LANGUAGE_START_CYCLE);
while (yield take(channel)) {
while (true) {
const { stopped } = yield race({
wait: call(wait, 3000),
stopped: take(ActionTypes.LANGUAGE_STOP_CYCLE)
});
if (!stopped) {
yield put(actions.cycleLanguage());
} else {
break;
}
}
}
}
// sagas.js (root sagas)
export default function * sagas() {
yield [
directorySaga(), // Another saga which works fine
pusherSaga(), // Another saga which works fine
languageSaga()
]
}
我正在使用的其他一个传奇的例子:
// directorySaga.js
function * fetchDirectory(action) {
try {
const directory = yield call(Api.fetchDirectory, action.id);
yield put(fetchDirectorySucceeded(directory));
} catch (e) {
yield put(fetchDirectoryFailed(e.message));
}
}
export default function * directorySaga() {
yield * takeLatest(ActionTypes.DIRECTORY_REQUESTED, fetchDirectory);
}
答案 0 :(得分:1)
我将在这里回答我的问题。
上面的代码我工作,但当我触发操作时,我使用Redux Dev Tools将操作分派给商店。
我使用工具手动调度LANGUAGE_START_CYCLE
,这改变了状态 - 但显然这并没有通知saga中间件,我的频道从未更新过:
但在我的某个组件中使用简单按钮时:
<button onClick={() => dispatch(actions.startCycle())}>
Start
</button>
<button onClick={() => dispatch(actions.stopCycle())}>
Stop
</button>
通知了传奇中间件。
<强>更新强>
我的商店配置是:
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga';
import rootReducer from '../reducers/index';
import sagas from '../sagas/index';
export default function configureStore(initialState) {
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, initialState, compose(
applyMiddleware(sagaMiddleware),
window.devToolsExtension ? window.devToolsExtension() : f => f
));
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers');
store.replaceReducer(nextReducer);
});
}
sagaMiddleware.run(sagas);
return store;
}
答案 1 :(得分:0)
我认为wait函数类型错误。 你必须这样修理。
const wait = ms => {
return new Promise(resolve => {
setTimeout(() => resolve(), ms)
})
}