繁体   English   中英

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

[英]why counter value increment and decrement only first time?

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

  }
}

你好

能否请您告诉我为什么我的计数器值仅在第一次增加和减少。我有两个按钮increment和在按钮单击时decrement计数器的值变化。但是我的值仅在第一次更改。它显示0初始值是正确的,但是之后它为什么不起作用?

每次调用该函数都非常简单: 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);
  }

更改您的“ 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;
  }
}
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;
  }

暂无
暂无

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

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