簡體   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