All reducers will be invoked when an action is dispatched?

后端 未结 3 379
迷失自我
迷失自我 2020-12-08 06:23

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

相关标签:
3条回答
  • 2020-12-08 07:09

    You can ignore actions of specific reducer by using https://github.com/omnidan/redux-ignore

    import { combineReducers } from 'redux';
    // redux-ignore higher-order reducer
    import { ignoreActions } from 'redux-ignore'
     combineReducers({
      counter: ignoreActions(counter, [INCREMENT_COUNTER])
    });
    

    Also read about performance on official site https://redux.js.org/faq/performance/#wont-calling-all-my-reducers-for-each-action-be-slow

    0 讨论(0)
  • 2020-12-08 07:10

    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.

    0 讨论(0)
  • 2020-12-08 07:12

    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)

    0 讨论(0)
提交回复
热议问题