代码之家  ›  专栏  ›  技术社区  ›  user944513

为什么反增值和反增值只是第一次?

  •  0
  • user944513  · 技术社区  · 8 年前

    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 初始值哪一个是正确的,但之后它就不起作用了,为什么?

    3 回复  |  直到 8 年前
        1
  •  0
  •   MukulSharma    8 年前
    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;
      }
    
        2
  •  2
  •   Swoox    8 年前

    每次调用函数时都非常简单: 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);
      }
    
        3
  •  0
  •   Eliseo    8 年前

    改变你的“反减速器功能”

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