【问题标题】:Update the state of one reducer based on state of another reducer根据另一个 reducer 的状态更新一个 reducer 的状态
【发布时间】:2017-01-27 02:17:06
【问题描述】:

我在减速器中有一个状态,看起来像这样:

此状态处理当前用户的选择。

const selection = {
  timespan: "-3660",
  customTimespan: false,
  pathIds: [''],
  source: undefined,
  direction: 0,
  appClassIds: []
};

我在另一个 reducer 中有另一个 state,它有一个 appClasses 项目列表,用户可以在树上打开或关闭这些项目。

状态是 appClasses。

问题是,当用户选择某些内容时,我会更新 appClasses 状态,但我还必须根据 appClasses 的新状态更新 selection.appClassIds。

我的问题是如何根据另一个减速器的状态更新减速器的状态?还是我必须将这些状态合并为一个状态?

类似:

const initialState = {
appClasses = [],
selection: {
  timespan: "-3660",
  customTimespan: false,
  pathIds: [''],
  source: undefined,
  direction: 0,
  appClassIds: []
 }
};

【问题讨论】:

  • 确认 - reducer 本质上是无状态的 - 就像...它们是定义上的纯函数并且不维护任何状态。您是在问:“我如何在我的 redux 应用程序中处理横切关注点?”
  • 嗯,是的,正如我所说,我有两个减速器,一个取决于另一个的状态。
  • 请参阅有关该主题的 Redux 常见问题解答条目,地址为 redux.js.org/docs/faq/Reducers.html#reducers-share-state

标签: javascript reactjs redux react-redux


【解决方案1】:

你可以这样做:

function a(state, action) { }
function b(state, action, a) { } // depends on a's state

function something(state = {}, action) {
  let a = a(state.a, action);
  let b = b(state.b, action, a); // note: b depends on a for computation
  return { a, b };
}

干杯:)

【讨论】:

    猜你喜欢
    • 2016-12-01
    • 2018-11-15
    • 2017-03-07
    • 1970-01-01
    • 2019-04-01
    • 2018-01-02
    • 2019-07-28
    • 2017-04-02
    • 1970-01-01
    相关资源
    最近更新 更多