如何基于异步调度的动作执行多个生成器

IT技术 reactjs react-redux redux-saga
2021-05-09 16:59:37

我正在尝试分派多个动作,这些动作将触发多个生成器功能。

点击

dispatch({ type: "ACTION_1", data1});
dispatch({ type: "ACTION_2", data2});

传奇.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,method1 被调用,我可以看到一个网络调用,并且在 console 上有这个错误Error: Generator is already running

我试图takeEvery在好actionWatcher()方法,同样的错误。

我如何实现这一目标?

1个回答

根据要求,我们可以创建像这里 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.where 我们正在配置我们的商店,然后运行我们的传奇。喜欢

/**
 *  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;