In Redux, accessing the global store state within action creators can be a contentious topic. Here we'll delve into two approaches for state access in action creators and explore their pros and cons.
import store from '../store'; export function someAction() { return { type: SOME_ACTION, items: store.getState().otherReducer.items, } }
This method directly imports the store, relying on it being a singleton exported from a module. While functional, it's discouraged due to server-rendering limitations, where separate stores are often required per request.
export function someAction() { return (dispatch, getState) => { const {items} = getState().otherReducer; dispatch(anotherAction(items)); } }
This approach utilizes Redux Thunk middleware, a recommended technique. Thunk allows action creators to dispatch functions instead of plain action objects, providing access to the dispatch and getState functions. While it requires middleware, it works seamlessly for both client and server-side rendering.
Ultimately, the best approach depends on individual application requirements. Ideally, actions should contain minimal information; however, it's acceptable to use getState in action creators when necessary. Consider the pros and cons of both approaches and choose the one that aligns best with your project.
The above is the detailed content of When is State Access in Redux Action Creators Right for You?. For more information, please follow other related articles on the PHP Chinese website!