我正在尝试调度将触发多个生成器功能的多个动作。
OnClick
dispatch({ type: "ACTION_1", data1});
dispatch({ type: "ACTION_2", data2});
saga.js
function* method1(action){
//...
const response = yield call(api, requestParams);
//...
}
function* method2(action){
//...
const response1 = yield call(api, requestParams1);
//...
//dependent on response1
const response2 = yield call(api, requestParams2);
//...
//dependent on response2
const response3 = yield call(api, requestParams3);
//...
}
function* actionWatcher() {
yield all([
takeLatest("ACTION_1", method1),
takeLatest("ACTION_2", method2),
]);
}
export default function* sagas() {
yield all([actionWatcher()]);
}
OnClick,方法1被调用,我可以看到网络呼叫,并且在控制台Error: Generator is already running
上出现此错误。
我也在takeEvery
方法中尝试过actionWatcher()
,同样的错误。
我该如何实现?
根据要求,我们可以在此处创建sagas,例如method1Saga和method2Saga是必需的,因此,我给您提供一个示例,说明saga的工作原理
//worker : work for our saga
function* method1(action) {
// api call : if we have many dependent api calls then we can simply add
//one more response2 below response1 and we can use response1 in response2 as well because yield wait until we get our response from server
const response1 = yield call(api, requestParams); // api call which return type and payload
const response2 = ......
yield put(pass_final_response_here); // pass_final_response_here like ( { type : '' , payload : 'your_response' } )
}
//watcher : watch for request
function* method1Saga() {
yield takeLatest("ACTION_1",method1)
}
//您可以按照上述示例创建method2Saga
function* actionWatcher() {
yield all([
method1Saga(),
//pass your all saga here
]);
}
最后导入actionWatcher。在这里我们配置商店,然后运行我们的传奇。喜欢
/**
* Store Configuration
*/
import { createStore , applyMiddleware } from 'redux';
import rootReducer from 'your_root_reducer_path';
//middleware
import reduxSaga from 'redux-saga';
//actionWatcherPath
import actionWatcherPath from 'actionWatcherPath'; //
const sagaMiddleware = reduxSaga();
//store
const store = createStore(rootReducer,applyMiddleware(sagaMiddleware));
//run : our actionWatcherPath
sagaMiddleware.run(actionWatcherPath);
export default store;