All reducers will be invoked when an action is dis

2019-02-01 17:56发布

问题:

I am using combineReducers to combine all the reducers to create the store, does it mean that any action dispatched from any view will trigger all the reducers being invoked to check the action type?Is it kind of low efficiency?

Or I don't fully understand the redux design principle?

回答1:

Yes, that is correct.

However one option you have to optimize this behaviour (suggested from the Redux docs) is to use 'reselect' https://github.com/rackt/reselect

Reselect basically allows you to create memoized selectors, whereby you can say that props A depends on state B and state C, and therefore only recompute props A if state B or state C changes.

Notice that this will still trigger all of the reducers to run (and go through the switch statement to see if the action might apply to them) - I believe there is no way around this behaviour. Using reselect however means that your top level component will only receive a prop/state change if there was an actual change that affects that state, rather than triggering a change every time and making React re-render everything, even when the change had no effect because it was somewhere unrelated. (The readme in reselect explains better)



回答2:

Yes - all the reducers will get called when you dispatch the action. You will get one nice side effect to it. Because every reducer returns default state if the action isn't found you get your initial state set up with a single action.

It could be beneficial, although I haven't tried it yet, to have single action affecting multiple reducers aka changing the state in two different part of the store.

When you add reselect to it as @luanped suggested you can get a lot of sick results!

My current stack is:

  • Redux for state, actions management
  • Reselect for data transformation layer
  • React for views

Adding reselect to the work flow and making it work alongside reducers was the best thing that happened to me last week.



标签: redux