javascript - Angular 6 + Ngrx 状态值更新而不使用操作

标签 javascript angular typescript rxjs ngrx

我有一个简单的状态:

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

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

还有一个选择器:

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

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

在我的组件中,我使用选择器:

 public item: Item  = {} as Item;

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

但是当我通过执行以下简单操作来更新此本地 Item 时:

this.item.value = someValue;

this.item.value 将在 ItemsState 中更新,无需使用任何操作。

这怎么可能?

最佳答案

这是因为该项目共享相同的引用。如果您更新它,您在商店中的商品也会更新。

这不是你想要的。要在开发过程中捕获这些“错误”,您可以使用包 ngrx-store-freeze以防止这种情况发生。

关于javascript - Angular 6 + Ngrx 状态值更新而不使用操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52875149/

相关文章:

javascript - 从变量切换函数

javascript - 添加 Ajax 内容后单击事件不工作

javascript - Angular2 使用正则表达式验证输入

Angular 2 : Global AppInjector. 如何避免警告 "circular dependency"

javascript - Jasmine 错误 - .div 上触发了预期事件 [object Object]

javascript - JS - 查看 if 语句中哪个 "or"评估为 true

angular - 升级到 Angular 9 后,编译时间大幅增加

javascript - Angular,在路由更改时更新组件

javascript - React.useMemo 无法防止重新渲染

javascript - Angular 2+ 中的 'nested' 组件怎么样?