【问题标题】:ngRx action not dispatching correctlyngRx 操作未正确分派
【发布时间】:2020-07-06 16:58:27
【问题描述】:

我正在尝试使用 ngRx 为我的应用程序提供全局存储,以便在需要时访问和更改内容。最大的问题是我不明白为什么我发送的操作没有改变我的应用程序中的任何内容。我已经使用 Redux devtools 来查看代码是否被触发,但不是,并且我所做的任何 console.log 命令也停止工作。我是否需要在 ngRx 中使用我缺少的其他部分?类型

动作:

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

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

减速机:

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

使用的普通代码:

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

【问题讨论】:

  • 你可能没有在store.forRoot(...)注册reducer?
  • 请与商店初始化分享您的AppModule 代码。
  • @AdrianBrand 感谢您告诉我有关依赖注入的信息!我的应用程序的概念化和处理要容易得多。我可能会再次尝试使用更复杂的 Rxjs 来保证繁重的样板代码。
  • 在开始学习 Angular 之前先学习 RxJs。 Angular 是基于 RxJs 构建的。你永远不会找到保证 ngrx 的用例,商店模式解决了 Angular 中不存在的 React 问题。

标签: javascript angular ngrx


【解决方案1】:

如果你的 action 没有被调度,(在 devtools redux 中没有跟踪),你应该检查你的 store 是否正确初始化。

此外,如果设置正常,可能是由于您的减速器实现。

Reducer 函数必须改变状态并返回复制的版本,但不能返回相同的实例引用。

你的代码应该是:

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

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 2017-10-11
    • 2017-02-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    相关资源
    最近更新 更多