Accessing Redux State in Action Creators
Redux actions are typically designed to be "thin" and contain only the necessary information to update the application state. However, in some scenarios, it may be necessary to access the global store state within an action creator. This article explores two approaches for doing so and provides guidance on their usage.
Using a Singleton Store
One approach involves importing a singleton store and accessing its state directly.
import store from '../store'; export const SOME_ACTION = 'SOME_ACTION'; export function someAction() { return { type: SOME_ACTION, items: store.getState().otherReducer.items, } }
While this approach is simple to implement, it heavily relies on the store being a singleton and exposed as a module import. This design is discouraged as it hinders the implementation of server rendering, where separate store instances are typically required per request.
Using Redux Thunk Middleware
The recommended approach is to leverage Redux Thunk middleware. Thunk middleware allows asynchronous functions to be dispatched as actions, providing access to the getState() method.
export const SOME_ACTION = 'SOME_ACTION'; export function someAction() { return (dispatch, getState) => { const {items} = getState().otherReducer; dispatch(anotherAction(items)); } }
This approach requires using Redux Thunk, but it allows for flexible access to the store state on both the client and server environments.
Considerations
The use of getState() in action creators has been debated in the Redux community. While some developers advocate against it, others believe it's acceptable in specific scenarios, such as conditional dispatches or accessing cached data.
Ultimately, the best approach depends on the specific application requirements. If access to the store state is necessary within an action creator, either the singleton store or Thunk middleware options can be considered. However, it's important to note that actions should generally be kept "thin" to maintain clarity and traceability.
The above is the detailed content of How to Access Redux State within Action Creators?. For more information, please follow other related articles on the PHP Chinese website!