Update the state of one reducer based on state of

2019-07-22 07:49发布

问题:

I've got an state in a reducer with a state that looks like this:

This state handles the current user selections.

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

And I have another state in another reducer that has a list of items appClasses that the user can toggle on or off on a tree.

The state is appClasses.

The thing is that when the user selects something I update appClasses state but also I have to update selection.appClassIds depending on the new state of appClasses.

My question is how can I update a state of a reducer based on the state of another reducer? Or do I have to combine the states in one state?

Something like:

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

回答1:

You can do like this:

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

Cheers:)