问题
At the moment I'm creating actions and then a reducer to handle different parts of my app... the different domains.
My app lists classes and pupils.
Currently I have an action that the app has loaded so that I know when to remove the loading spinner, I have actions for classes and pupils. My problem is that I find I need to execute several actions in a row and am not sure if this is a valid way to use redux.
Here is an example function that dispatches several actions after the data is loaded:
/**
* Callback used by readAppData.
*
* @param object ioResult An object: {success: boolean, errorObj?: object, data?: string}
*/
dataLoaded(ioResult: Object) {
if (ioResult.success === true) {
this.props.dispatch(appActions.appHasLoaded());
if (ioResult.data !== '') {
const jsonData = JSON.parse(ioResult.data);
this.props.dispatch(classActions.replaceClasses(jsonData.classes));
this.props.dispatch(pupilActions.replacePupils(jsonData.pupils));
}
} else if (ioResult.errorObj.code === 'ENOENT') { // File doesn't exist.
writeAppData('', this.dataSaved);
} else { // Some other error.
this.props.dispatch(appActions.appHasErrored());
}
}
I was thinking about putting the jsonData.classes and jsonData.pupils into the appActions.appHasLoaded() call and just have a new case for APP_HAS_LOADED in my classes and pupils reducers.
Is this a better approach? To reduce it down to one action? Having separate actions makes it easy to see what is happening... maybe in 6 months time I will have to look through my code to work out exactly what happens on APP_HAS_LOADED if I use it in other reducers. Also the data that is loaded on app start is going to expand beyond just classes and pupils so if I don't combine the calls there could soon be many more dispatches to make - maybe I can store the data in separate files and load each one one at a time which would also fix my problem of having to call mutiple actions in a row.
Is it OK to call dispatch multiple times?
回答1:
Yes, you can.
From Redux creator Dan Abramov:
Many reducers may handle one action. One reducer may handle many actions.
Referenced in Redux Docs
also, there is a conversation on github about this.
来源:https://stackoverflow.com/questions/48052571/is-it-ok-for-a-reducer-to-listen-to-other-actions