简体   繁体   English

ngRx 操作未正确分派

[英]ngRx action not dispatching correctly

I am trying to use ngRx to have a global storage for my app to access and change things whenever it needs to.我正在尝试使用 ngRx 为我的应用程序提供全局存储,以便在需要时访问和更改内容。 The big problem is that I don't understand why my action that I dispatch is not changing anything in my app.最大的问题是我不明白为什么我发送的操作没有改变我的应用程序中的任何内容。 I have used Redux devtools to see if the code is being fired but it's not, and any console.log commands I do also stop working.我已经使用 Redux devtools 来查看代码是否被触发但不是,并且我所做的任何 console.log 命令也停止工作。 Do I need to use some other part to ngRx that I'm missing?我是否需要在 ngRx 中使用我缺少的其他部分? Ty

Actions:行动:

    export class changeTransactions implements Action {
  type = 'CHANGE_TRANSACTIONS';
  constructor(public payload: any[]) {
  }
}

export class addTransaction implements Action {
  type = 'ADD_TRANSACTION';
  constructor(public payload: any) {
  }
}

Reducer:减速器:

export function reducer(state: State = initialState, action: any) {
  switch(action.type) {
    case 'ADD_TRANSACTION': {
      state.transactions.unshift(action.payload);
      return state;
    }
    case 'LOAD_TRANSACTIONS': {
      return state.transactions;
    }
    default:
      return state;
  }
}

Normal Code used:使用的普通代码:

    this.observable$ = this.store.select('info');
        this.observable$.subscribe(info => {
          console.log(info);
          this.transactions = info.transactions;
          this.accounts = info.accounts;
        });
this.store.dispatch(new infoActions.addTransaction(fakeTransactions));

If you're action is not dispatched, (no trace in devtools redux), you should check if your store is correctly initialized.如果您的操作未调度,(在 devtools redux 中没有跟踪),您应该检查您的商店是否已正确初始化。

Moreover, if setup is ok, it could be due to your reducer implementation.此外,如果设置正常,则可能是由于您的减速器实施所致。

Reducer function must mutate state and return a copied version but not the same instance reference. Reducer function 必须改变 state 并返回一个复制的版本,但不是相同的实例引用。

Your code should be:您的代码应该是:

export function reducer(state: State = initialState, action: any) {
  switch(action.type) {
    case 'ADD_TRANSACTION': {
      // return a copied version of state, with mutation, never the same reference.
      return {
        ...state,
        transactions: [...state.transactions, action.payload]
      }
    }
    case 'LOAD_TRANSACTIONS': {
      // be careful to return state here, and not state.transactions !
      //return state.transactions;

      return state;
    }
    default:
      return state;
  }
}

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

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