NgRx异常行为

时间:2019-10-21 19:33:34

标签: angular ngrx

我来自React / Redux,我真的错过了一些愚蠢的事情吗?

仅在AddItem分发部分中进行更改。 情况1:未按预期工作,每个新项都使用后继者uuid进行更新,并始终绑定到NgModel输入

export class AppComponent implements OnInit {
  shoppingItems$: Observable<Array<ShoppingItem>>;
  newShoppingItem: ShoppingItem = {
    id: uuid(),
    name: ''
  };

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

  ngOnInit() {
    this.shoppingItems$ = this.store.select(store => store.shopping);
  }

  addItem(name: string) {
    this.newShoppingItem.id = uuid();
    this.store.dispatch(new AddItemAction(this.newShoppingItem));
  }

  removeItem(id: string) {
    this.store.dispatch(new RemoveItemAction(id));
  }
}

HTML部分(第二种情况也保持相同)

<form (ngSubmit)="addItem()">
  <input
    type="text"
    [(ngModel)]="newShoppingItem.name"
    placeholder="name"
    name="itemName"
  />
  <button type="submit">SUBMIT</button>
</form>

<ul>
  <li *ngFor="let item of shoppingItems$ | async" (click)="removeItem(item.id)">
    {{ item.id }} - {{ item.name }}
  </li>
</ul>
import {
  ShoppingAction,
  ShoppingActionsTypes
} from '../actions/shopping.actions';
import { ShoppingItem } from './../models/shopping-item.model';
const initialState: Array<ShoppingItem> = [
  {
    id: 'Ok Bro',
    name: 'Mauro'
  }
];

export function ShoppingReducer(
  state: Array<ShoppingItem> = initialState,
  action: ShoppingAction
) {
  switch (action.type) {
    case ShoppingActionsTypes.ADD_ITEM:
      return [...state, action.payload];
    case ShoppingActionsTypes.REMOVE_ITEM:
      return state.filter(item => item.id !== action.payload);
    default:
      return state;
  }
}

情况2:工作正常

addItem(name: string) {
    this.newShoppingItem.id = uuid();
    this.store.dispatch(new AddItemAction(this.newShoppingItem));
    this.newShoppingItem = {
      id: '',
      name: ''
    }
  }

1 个答案:

答案 0 :(得分:2)

在分派操作时,将保留对表单模型的引用。

以下方法应该起作用:

 this.store.dispatch(new AddItemAction({...this.newShoppingItem}));