简体   繁体   中英

How do I share readonly state between two or more reducers

I need access to user editable state from two or more reducers. Is there a way to access state controlled by another reducer without passing it to the reducer through the action's payload? I want to avoid having every action send user settings to reducers.

State

{
  userSettings: {
    someSetting: 5
  },
  reducer1State: {
    someValue: 10 // computed with userSettings.someSetting
  },
  reducer2State: {
    someOtherValue: 20 // computed with userSettings.someSetting
  }
} 

From the reducer1 I would like to get at userSettings.someSetting using something like the following:

function update(state={}, action) {
  if (action.type === constants.REDUCER_1.CALCULATE) {
    return _.assign({}, state, {
      someValue: 2 * GETSTATE().userSettings.someSetting
    });
  }
...

I do not want to have to send userSettings from the action like this:

export function calculate(userSettings) {
  return {
    type: constants.REDUCER_1.CALCULATE,
    userSettings: userSettings
  };
}

One of the golden rules of Redux is that you should try to avoid putting data into state if it can be calculated from other state, as it increases likelihood of getting data that is out-of-sync, eg the infamous unread-messages counter that tells you that you have unread messages when you really don't.

Instead of having that logic in your reducer, you can use Reselect to create memoized selectors that you use in your connectStateToProps function, to get your derived data, eg something along the line of this:

const getSomeSettings = state => state.userSettings.someSetting;
const getMultiplier = state => state.reducer1.multiplier;

const getSomeValue = createSelector([getSomeSettings, getMultiplier],
    (someSetting, multiplier) => {

});

const mapStateToProps(state) => {
    return {
        someValue: getSomeValue(state)
    }
}

const MyConnectedComponent = connect(mapStateToProps)(MyComponent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM