简体   繁体   English

如何在两个或更多减速器之间共享只读状态

[英]How do I share readonly state between two or more reducers

I need access to user editable state from two or more reducers. 我需要从两个或更多Reducer访问用户可编辑状态。 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. 我想避免让每个操作都将用户设置发送给reducer。

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: 从reducer1我想得到userSettings.someSetting使用类似如下的东西:

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: 我不想像这样从动作发送userSettings:

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. Redux的一个重要规则是,如果可以从其他状态计算数据,则应该尽量避免将数据置于状态,因为这会增加获取不同步数据的可能性,例如臭名昭​​着的未读消息计数器告诉你,如果你真的没有,你有未读的消息。

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: 您可以使用Reselect创建在connectStateToProps函数中使用的memoized选择器,而不是在reducer中使用该逻辑,以获取派生数据,例如:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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