为什么计数器值仅在第一次增加和减少?

时间:2018-06-25 14:29:56

标签: javascript angular ngrx ngrx-store

https://stackblitz.com/edit/angular-q8nsfz?file=src%2Fapp%2Fapp.component.ts

import {Component, OnInit} from '@angular/core';
import {Store} from '@ngrx/store';
import {Observable} from 'rxjs';

import * as fromApp from './app.store';
import {DecrementCounter, IncrementCounter} from './store/counter.action';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  c: Observable<object>;

  constructor(private store: Store<fromApp.AppState>) {
  }

  incrementCounter() {
     this.store.dispatch(new IncrementCounter());
  }

  decrementCounter() {
    this.store.dispatch(new DecrementCounter());
  }
  ngOnInit(){
    this.c =this.store.select('counterValue');

  }
}

您能告诉我为什么我的计数器值仅第一次增加和减少吗?我有两个按钮incrementdecrement,单击按钮时计数器的值发生变化。但是我的值仅第一次发生变化。它显示0初始值是正确的,但此后为什么不起作用?

3 个答案:

答案 0 :(得分:2)

每次调用该函数非常简单:incrementCounter创建一个新类new IncrementCounter()。因此,每次调用此函数时,都会执行相同的操作。

您需要做的是在组件范围内创建这个新类:

private incrementClass = new IncrementCounter();
private decrementClass = new DecrementCounter();

  constructor(private store: Store<fromApp.AppState>) {
  }

  incrementCounter() {
     this.store.dispatch(this.incrementClass);
  }

  decrementCounter() {
    this.store.dispatch(this.decrementClass);
  }

答案 1 :(得分:0)

更改“ counterReducer功能”

export function counterReducer(state = initialState, action: CounterActions.CounterManagment) {
  switch (action.type) {
    case CounterActions.INCREMENT:
      const counter = initialState.counter++; //see, you increment the variable initialState.counter, and then return it
      return {...state, counter};
    case CounterActions.DECREMENT:
      const currentCounter = initialState.counter--;
      return {...state, counter: currentCounter}; //idem decrement
    default :
      return state;
  }
}

答案 2 :(得分:0)

Replace initialState.counter + 1 to state.counter + 1;

  switch (action.type) {
    case CounterActions.INCREMENT:
      const counter = state.counter + 1;
      return {...state, counter};
    case CounterActions.DECREMENT:
      const currentCounter = state.counter - 1;
      return {...state, counter: currentCounter};
    default :
      return state;
  }