简体   繁体   English

Angular 6 + Ngrx状态值更新,无需使用操作

[英]Angular 6 + Ngrx state value update without using action

I have a simple state : 我有一个简单的状态:

export interface ItemsState{
  items: Item[],
  otherItem: OtherItem,
}

const initialState: ItemsState= {
  items: [],
  otherItem: {} as OtherItem,
}

And a selector : 还有一个选择器:

const getItemFeatureState = createFeatureSelector<ItemsState>('items');

export const getItemValue= createSelector(
  getItemFeatureState,
  state => state.otherItem,
);

In my component I use the selector : 在我的组件中,我使用选择器:

 public item: Item  = {} as Item;

 constructor(private itemsStore: Store<fromItem.State>) {
    this.itemsStore.pipe(
      select(fromItem.getItemValue),
      distinctUntilChanged(),
    ).subscribe(item=> this.item = item);
}

But when I update this local Item by doing something simple like : 但是当我通过做一些简单的事情来更新本地Item

this.item.value = someValue;

this.item.value will be updated in ItemsState without using any Actions. this.item.value将在ItemsState中更新,而无需使用任何操作。

How is that possible ? 那怎么可能呢?

This is because the item is sharing the same reference. 这是因为该项目共享相同的参考。 If you update it, your item in the store will also be updated. 如果您更新它,那么商店中的商品也将被更新。

This is NOT what you want. 这不是您想要的。 To catch these "mistakes" during development you can use the package ngrx-store-freeze to prevent this. 要在开发过程中发现这些“错误”,可以使用软件包ngrx-store-freeze来防止这种情况。

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

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