Should I run all saga when launch app?

六眼飞鱼酱① 提交于 2021-01-27 12:52:26

问题


I've just started to learn and use redux-saga, at first I thought it worked this way: first you make action which is connected to saga, then saga detects action,calls api which returns data and saga returns this data to reducer. I built 2 testing saga files and one root saga (I wanted to make rootSaga, like combineReducer), so this is my rootSaga :

import * as SpreadsheetSagas         from "../pages/spreadsheet/containers/spreadsheet/spreadsheet.saga";
import * as SpreadsheetFilterSagas   from "../pages/spreadsheet/containers/spreadsheet_filter/spreadsheet_filter.saga";

export default function* rootSaga() {
  yield all([
    ...Object.values(SpreadsheetSagas),
    ...Object.values(SpreadsheetFilterSagas)
  ].map(fork))
}

and this is one of my saga function:

export function* getData() {
   const response = yield call(ApiService.get);
   const payload = response ? response.data : {};
   //send returned object back to reducer as payload:
   yield put({ type: 'GET_MOCK_DATA', payload});
}

and my store folder looks like:

const middleWare = [];

// Setup Redux-Saga.
const sagaMiddleware = createSagaMiddleware();
middleWare.push(sagaMiddleware);

const store = createStore(rootReducer, {}, 
compose(applyMiddleware(...middleWare)));

// Initiate the root saga.
sagaMiddleware.run(rootSaga);

So, when I run my app, it calls every saga functions - and this is correct way to implement sagas :? or I should have several rootSaga files which will be depend on current page, and then when I open page, run appropriate rootSaga? I hope I explained everything correctly :/ please give me any suggestions. thank you.


回答1:


I think generally you just have one tree of sagas that relate to your entire app, not multiple root sagas for different pages/routes. You just attach the rootSaga once, as middleware.

So yes, when your app starts the entire tree of sagas starts and beings watching actions. Sagas interact globally with your store, so it makes sense for them to start globally with your app.

Only start the sagas that watch for actions (using take, takeEvery etc). Other sagas that make side effects, or call apis, shouldn't be invoked when your app starts.

Creating a tree of sagas similar to reducers and combineReducer is the right way to go too.



来源:https://stackoverflow.com/questions/51855748/should-i-run-all-saga-when-launch-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!