简体   繁体   中英

ngrx/store How to create dependent reducers

I'm pretty new to redux and in particular ngrx/store. I couldn't find an example about this topic and I hope you guys can point me in the right direction. What I'm trying to achieve is a component called freedownloads that dispatches an action that should update the state of another component called counter. In particular the boolean value canDownload. At the moment I have 2 reducers. Should I use combineReducers ? Do you have any examples ? I'm using the latest version of ngrx/store (2.1.2)

Thank you very much!

//counter.ts
...
export const counter = (state: CounterState = initialState, action: Action) => {
  switch (action.type) {
    case DECREMENT:
      let isZero:boolean = (state.counter - 1) > 0;
      return Object.assign({}, state, {
        counter: state.counter - 1,
        canDownload: isZero
      });
    case INCREMENT:
      return Object.assign({}, state, {
        counter: state.counter + 3,
        canDownload: true
      });

    default:
      return state;
  }
}


//freedownloads.ts
...
export const freedownloads = (state: boolean = false, action: Action) => {

  switch (action.type) {
    case ENABLE:
      return true;
    case DISABLE:
      return false;
    default:
      return state;
   }
}

Assuming I understand your question...

Your actions should be shared across reducers since ngrx has only one store which is a combination of all reducers registered with provideStore. You just check for that action name in both reducers and then perform the logic you need for each state slice there. This is why each reducer needs to return as default the state passed in when no action matches a switch case value.

So I'd guess your code would need to be something like this.

export const counter = (state: CounterState = initialState, action: Action) => {
  switch (action.type) {
    case DECREMENT:
      let isZero:boolean = (state.counter - 1) > 0;
      return Object.assign({}, state, {
        counter: state.counter - 1,
        canDownload: isZero
      });
    case ENABLE:
      return Object.assign({}, state, {
         canDownload: true
      });
    case INCREMENT:
      return Object.assign({}, state, {
    counter: state.counter + 3,
    canDownload: true
  });

default:
  return state;
  }
}

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