嗨,我使用 Ngrx 作为我的前端项目的状态管理。最近我发现更新状态中的一个字段时会触发所有订阅。
假设我有一个包含字段 A 和 B 的状态。相应地,我有 AComponent 和 BComponent 订阅了 A 和 B 的值。现在如果我继续调度一个动作来更新 A。即使 B 的订阅也将一直被触发B 的值没有更新。
目前我在做的是在B的订阅函数中,查看值是否改变了,比如
if (this.B !== B) {
//do something
}
有没有什么办法,如果我调度一个动作来更新A,不触发B的订阅?或者这就是NGRX的基本机制?
谢谢
更新
这是我正在使用的选择器
this._store
.select("appState")
.pipe<T>(pluck("B"))
.subscribe(callback);
更新 2
根据@Anarno 的回答,我添加了选择器如下
const BFeatureSelector = createFeatureSelector<string>('b');
export const BSelector = createSelector(
BFeatureSelector,
state => state
);
同时,我在 reducer 中打印一条消息以确保 B 更新为
case app.ActionType.B: {
console.info("b is update in reducter");
return Object.assign({}, state, { b: action.payload });
}
然后我在 BComponent 中使用这个 BSelector 有以下三种方法
this._store.select(BSelector).subscribe(b=> {
console.info("b is updated 1");
console.info(b);
});
this._store
.pipe(
map(state => BSelector(state))
)
.subscribe(b=> {
console.info("b is updated 2");
console.info(b);
});
this._store
.pipe(select(notificationSelector))
.subscribe(b=> {
console.info("b is updated 3");
console.info(b);
});
我观察到的是,b is updated 1
并且b is updated 3
仅在组件初始化时打印一次,而b is updated 2
在状态中的其他字段更新时一直打印。但是,console.info(b);
每种方法都不起作用。所有三种方法都不会打印 b 的内容。
您需要一个选择器文件,并像这样制作选择器:
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { BState } from '../../../reducers/index';
const selectBState = createFeatureSelector<BState>('BState');
export const selectBvalue = createSelector(
selectBState,
state => state.value
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句