Home >Web Front-end >JS Tutorial >How Should Redux Action Creators Access State: From Store or Thunk?
Accessing Redux State Within Action Creators
Question:
In a Redux application, how can one access the global store state from within an action creator? Are the following approaches appropriate?
Approach 1:
<code class="javascript">import store from '../store'; export const SOME_ACTION = 'SOME_ACTION'; export function someAction() { return { type: SOME_ACTION, items: store.getState().otherReducer.items, } }</code>
Approach 2:
<code class="javascript">export const SOME_ACTION = 'SOME_ACTION'; export function someAction() { return (dispatch, getState) => { const {items} = getState().otherReducer; dispatch(anotherAction(items)); } }</code>
Answer:
The acceptability of accessing state within action creators is a topic of debate within the Redux community.
Approach 1:
Accessing state directly via store.getState() is discouraged because it relies on store being a global singleton. On the server, where separate stores may exist per request, this approach is problematic.
Approach 2:
This approach is preferred as it uses Redux Thunk middleware, which allows for asynchronous actions and retrieval of the store state via getState(). Thunk works seamlessly on both the client and server and ensures state access is isolated to the specific action.
Considerations:
Ultimately, both approaches can yield desired results, but Approach 2 is the recommended best practice for avoiding potential pitfalls and maintaining consistency across environments.
The above is the detailed content of How Should Redux Action Creators Access State: From Store or Thunk?. For more information, please follow other related articles on the PHP Chinese website!