admin管理员组

文章数量:1278983

There seems to be agreement that if an action creator needs state information (and we want to be independent of state shape), the ponent calling the action should submit the required state slices to the action. See e.g. Dan Abramov's ment here

But why are we not instead importing selectors into actions?

import { mySelector } from '../reducers';

const myAction = () => (dispatch, getState) => {
  const requiredState = mySelector(getState());
  etc...
};

It looks like this would save at least some state slices a roundtrip through ponents and de-couple things.

What's the disadvantage of doing this? (Except perhaps that actions cannot export ActionTypes.)

There seems to be agreement that if an action creator needs state information (and we want to be independent of state shape), the ponent calling the action should submit the required state slices to the action. See e.g. Dan Abramov's ment here

But why are we not instead importing selectors into actions?

import { mySelector } from '../reducers';

const myAction = () => (dispatch, getState) => {
  const requiredState = mySelector(getState());
  etc...
};

It looks like this would save at least some state slices a roundtrip through ponents and de-couple things.

What's the disadvantage of doing this? (Except perhaps that actions cannot export ActionTypes.)

Share Improve this question asked Jun 9, 2017 at 7:21 bebbibebbi 2,5393 gold badges26 silver badges36 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Yes, if you are going to access the store state in your action creators, thunks, or sagas, then you should use selector functions to encapsulate the lookup process.

The other aspect of your question is if accessing the store state in an action creator is a good idea. Dan has some reservations about it, and I understand where he's ing from, but from my point of view it's fine. I wrote a blog post that discusses a number of mon concerns about use of thunks, sagas, and state called Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability, and gave my reasons why I feel that those concerns are not generally real problems to worry about.

AFAIK the idea in the ment you mentioned is to "decouple" your action from state.

Decoupling the actions from the application state taking in the data you need from where the actions are called make the actions not bounded to state.

Usually decoupling is always a good thing, some advantages:

  • Easier to maintain code and change implementations
  • Easier unit test.
  • Less dependencies for your actions.

本文标签: javascriptRedux importing selectors into actionsStack Overflow